How to get an absolute file path in Python - Stack Overflow
文章推薦指數: 80 %
Given a path such as "mydir/myfile.txt" , how do I find the file's absolute path relative to the current working directory in Python? Home Public Questions Tags Users Companies Collectives ExploreCollectives Teams StackOverflowforTeams –Startcollaboratingandsharingorganizationalknowledge. CreateafreeTeam WhyTeams? Teams CreatefreeTeam CollectivesonStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. Learnmore Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. Learnmore HowtogetanabsolutefilepathinPython AskQuestion Asked 13years,7monthsago Modified 2monthsago Viewed 1.2mtimes 942 129 Givenapathsuchas"mydir/myfile.txt",howdoIfindthefile'sabsolutepathrelativetothecurrentworkingdirectoryinPython?E.g.onWindows,Imightendupwith: "C:/example/cwd/mydir/myfile.txt" pythonpathrelative-pathabsolute-path Share Improvethisquestion Follow editedDec27,2018at20:42 MadPhysicist 94.4k2323goldbadges148148silverbadges224224bronzebadges askedSep9,2008at10:19 izbizb 47.7k3939goldbadges114114silverbadges167167bronzebadges 0 Addacomment | 11Answers 11 Sortedby: Resettodefault Highestscore(default) Datemodified(newestfirst) Datecreated(oldestfirst) Helpusimproveouranswers.Aretheanswersbelowsortedinawaythatputsthebestansweratornearthetop? Takeashortsurvey I’mnotinterested 1373 >>>importos >>>os.path.abspath("mydir/myfile.txt") 'C:/example/cwd/mydir/myfile.txt' Alsoworksifitisalreadyanabsolutepath: >>>importos >>>os.path.abspath("C:/example/cwd/mydir/myfile.txt") 'C:/example/cwd/mydir/myfile.txt' Share Improvethisanswer Follow editedMay24,2017at22:23 JakeD 2,46311goldbadge1818silverbadges2828bronzebadges answeredSep9,2008at10:21 sherbangsherbang 14.6k11goldbadge2121silverbadges1616bronzebadges 8 38 Note:Onmostplatforms,thisisequivalenttocallingthefunctionnormpath()asfollows:normpath(join(os.getcwd(),path)).Soifmydir/myfile.txtdonotunderos.getcwd(),theabsolutepathisnottherealpath. – coanor Nov25,2014at4:15 37 @coanor?Withoutanexplicitroot,mydir/myfile.txtimplicitlyreferstoapathinsidethecurrentworkingdirectoryasisthereforeequivalentto./mydir/myfile.txt.Thatmightnotbethepathyouintendedtoinput,butitseemslikethecorrectinterpretationofthepathasfarasIcantell.Couldyouelaborate? – jpmc26 Jan8,2015at22:46 2 @jpmc26Idon'texactlyfollowcoanor,butIwouldsaythat(contrarytowhatIpresumed),thereisnolinkagebetweentheargumenttotheabspathfunctionandarealfile.Youcouldgiveanypathname-non-existentfilesanddirectoryheirarchiesarefine-andabspathwillsimplyresolvethebitsofthepath(includingtheparentdirectory".."element)andreturnastring.Thisisjustastringcomputedfromthecurrentdirectory;anycorrelationtoanactualfileisaccidental,itseems.Tryos.path.abspath("/wow/junk/../blha/hooey").Itworks. – MikeS Sep12,2018at2:01 2 @MikeSI'mhonestlynotsurewhythatwouldbeunexpectedbehavior.It'sabsolutepath,notabsolutefileordirectory.Ifyouwantanexistencecheck,callos.path.exists.Tothecontrary,systemslikePowerShellthatinsistonthepathexistingwiththestandardpathresolutionfunctionareapaintouse. – jpmc26 Sep12,2018at3:28 1 @jpmc26Toassumethatapathisjustastringthatlookslikeapathnameisnotclearatall,andgoescountertohowI'vebeenthinkingandspeakingofpathnamesformanyyears.IquotethePython3docsforabspath:"Returnanormalizedabsolutizedversionofthepathnamepath."Nota"...versionofthestringpath".Apathname,asdefinedbyPosix,is"Astringthatisusedtoidentifyafile."ThePythondocsareexplicitaboutrelpath:"thefilesystemisnotaccessedtoconfirmtheexistenceornatureofpath".Iftheargumenthereisobvious,whybeexplicitforrelpath? – MikeS Sep17,2018at18:07 | Show3morecomments 111 YoucouldusethenewPython3.4librarypathlib.(YoucanalsogetitforPython2.6or2.7usingpipinstallpathlib.)Theauthorswrote:"Theaimofthislibraryistoprovideasimplehierarchyofclassestohandlefilesystempathsandthecommonoperationsusersdooverthem." TogetanabsolutepathinWindows: >>>frompathlibimportPath >>>p=Path("pythonw.exe").resolve() >>>p WindowsPath('C:/Python27/pythonw.exe') >>>str(p) 'C:\\Python27\\pythonw.exe' OronUNIX: >>>frompathlibimportPath >>>p=Path("python3.4").resolve() >>>p PosixPath('/opt/python3/bin/python3.4') >>>str(p) '/opt/python3/bin/python3.4' Docsarehere:https://docs.python.org/3/library/pathlib.html Share Improvethisanswer Follow editedJun30,2016at16:30 MartijnPieters♦ 956k264264goldbadges37823782silverbadges31713171bronzebadges answeredOct24,2014at1:05 twasbrilligtwasbrillig 14.4k99goldbadges3939silverbadges6161bronzebadges 4 6 Veryhelpful.Usingos.path.abspath()gavemeanerror:AttributeError:'NoneType'objecthasnoattribute'startswith',usingPath().resolve()doesnotwiththesamerelativefilepath.(LinuxandPython3.4) – NuclearPeon Aug31,2015at16:14 2 Accordingtomyexperiment,inwindowplatform,resolve()returnsfullpathtoyouonlyifitisabletoresolve()file.But,os.path.abspathreturnsfullpathtoyouanywayeventhefiledoesnotexists.However,inlinux,italwaysreturnabsolutepath – MondWan Jul31,2020at9:04 WhyisthatwhenthePath(__file__)alone(withouttheresolvemethod)isusedinamodulebeingimportedalongwithapackage,givestheabsolutepathinsteadoftherelativepath? – aderchox Aug8,2020at8:50 1 Notethatresolve()willfollowsymlinks.Ifyoudon'twantthis,useabsolute()instead,whichwillleavenotresolvesymlinks. – BallpointBen Aug18,2021at16:09 Addacomment | 31 importos os.path.abspath(os.path.expanduser(os.path.expandvars(PathNameString))) Notethatexpanduserisnecessary(onUnix)incasethegivenexpressionforthefile(ordirectory)nameandlocationmaycontainaleading~/(thetildereferstotheuser'shomedirectory),andexpandvarstakescareofanyotherenvironmentvariables(like$HOME). Share Improvethisanswer Follow answeredMar7,2019at0:56 benjiminbenjimin 2,9702424silverbadges3838bronzebadges 1 Iknowthisisaratheroldanswer,butisn'tthereonecommandthatdoesallthisinonecall?Seemslikethiswouldbewhatwouldmaketheincomingpaththemostflexibleandhenceoftenneeded(atleastinmycasethat'strue). – FlorianBlume Oct5,2021at10:39 Addacomment | 31 Installathird-partypathmodule(foundonPyPI),itwrapsalltheos.pathfunctionsandotherrelatedfunctionsintomethodsonanobjectthatcanbeusedwhereverstringsareused: >>>frompathimportpath >>>path('mydir/myfile.txt').abspath() 'C:\\example\\cwd\\mydir\\myfile.txt' Share Improvethisanswer Follow editedOct4,2020at17:53 wim 299k8989goldbadges540540silverbadges687687bronzebadges answeredSep12,2008at6:53 TomTom 39.7k3333goldbadges9191silverbadges101101bronzebadges 5 3 Toobadtheynevergotaproperfilenameabstractionmoduleintothestdlib. – TorstenMarek Sep26,2008at12:08 1 @TorstenMarek:it'sasoreandlongstandingomission. – flow Feb11,2011at23:58 6 TheydidnowforPython3.4:pathlib.Seemyanswerinthisthread. – twasbrillig Oct24,2014at1:20 1 Thereareyyposinthisanswer.ItshouldbefrompathimportPaththenPath('mydir/myfile.txt').abspath() – frakman1 Jun5,2017at14:51 1 Therearenotypos,youmayhavebeenusingadifferentpathmodule.Thelinkedmoduleusesaclassnamedpath. – Tom Jun6,2017at23:42 Addacomment | 25 UpdateforPython3.4+pathlibthatactuallyanswersthequestion: frompathlibimportPath relative=Path("mydir/myfile.txt") absolute=relative.absolute()#absoluteisaPathobject Ifyouonlyneedatemporarystring,keepinmindthatyoucanusePathobjectswithalltherelevantfunctionsinos.path,includingofcourseabspath: fromos.pathimportabspath absolute=abspath(relative)#absoluteisastrobject Share Improvethisanswer Follow answeredDec27,2018at20:41 MadPhysicistMadPhysicist 94.4k2323goldbadges148148silverbadges224224bronzebadges Addacomment | 16 Todayyoucanalsousetheunipathpackagewhichwasbasedonpath.py:http://sluggo.scrapping.cc/python/unipath/ >>>fromunipathimportPath >>>absolute_path=Path('mydir/myfile.txt').absolute() Path('C:\\example\\cwd\\mydir\\myfile.txt') >>>str(absolute_path) C:\\example\\cwd\\mydir\\myfile.txt >>> Iwouldrecommendusingthispackageasitoffersacleaninterfacetocommonos.pathutilities. Share Improvethisanswer Follow editedMar10,2013at17:20 answeredMar10,2013at17:11 user9903user9903 Addacomment | 14 Thisalwaysgetstherightfilenameofthecurrentscript,evenwhenitiscalledfromwithinanotherscript.Itisespeciallyusefulwhenusingsubprocess. importsys,os filename=sys.argv[0] fromthere,youcangetthescript'sfullpathwith: >>>os.path.abspath(filename) '/foo/bar/script.py' Italsomakeseasiertonavigatefoldersbyjustappending/..asmanytimesasyouwanttogo'up'inthedirectories'hierarchy. Togetthecwd: >>>os.path.abspath(filename+"/..") '/foo/bar' Fortheparentpath: >>>os.path.abspath(filename+"/../..") '/foo' Bycombining"/.."withotherfilenames,youcanaccessanyfileinthesystem. Share Improvethisanswer Follow answeredFeb28,2019at15:26 LucasAzevedoLucasAzevedo 1,5331616silverbadges3131bronzebadges 1 2 Thisisnotwhatwasbeingasked.Theyaskedaboutapathinrelationtothecurrentworkingdirectory,whichisnotthesamethingasthescriptdirectory,thoughtheymaysometimesenduphavingthesamevalue. – TheElementalofDestruction May23,2019at4:16 Addacomment | 4 Youcanusethistogetabsolutepathofaspecificfile. frompathlibimportPath fpath=Path('myfile.txt').absolute() print(fpath) Share Improvethisanswer Follow answeredAug30,2021at14:44 DiaaM.ShalabiDiaaM.Shalabi 99844silverbadges1717bronzebadges 1 ThisanswerwasgivenwithmoredetailalreadybyMadPhysicistin2018. – MartinThoma Sep22,2021at11:45 Addacomment | 1 ifyouareonamac importos upload_folder=os.path.abspath("static/img/users") thiswillgiveyouafullpath: print(upload_folder) willshowthefollowingpath: >>>/Users/myUsername/PycharmProjects/OBS/static/img/user Share Improvethisanswer Follow answeredApr3,2018at21:12 chikwapurochikwapuro 1,25899silverbadges1010bronzebadges 1 4 Identicaltotheacceptedanswer,exceptitarrived10yearslate. – wim Oct4,2020at23:29 Addacomment | 1 Givenapathsuchasmydir/myfile.txt,howdoIfindthefile'sabsolutepathrelativetothecurrentworkingdirectoryinPython? Iwoulddoitlikethis, importos.path os.path.join(os.getcwd(),'mydir/myfile.txt') Thatreturns'/home/ecarroll/mydir/myfile.txt' Share Improvethisanswer Follow answeredFeb8at6:20 EvanCarrollEvanCarroll 1 Addacomment | 0 Incasesomeoneisusingpythonandlinuxandlookingforfullpathtofile: >>>path=os.popen("readlink-ffile").read() >>>printpath abs/path/to/file Share Improvethisanswer Follow answeredJul4,2018at19:09 BNDBND 52277silverbadges2121bronzebadges Addacomment | Highlyactivequestion.Earn10reputation(notcountingtheassociationbonus)inordertoanswerthisquestion.Thereputationrequirementhelpsprotectthisquestionfromspamandnon-answeractivity. Nottheansweryou'relookingfor?Browseotherquestionstaggedpythonpathrelative-pathabsolute-pathoraskyourownquestion. TheOverflowBlog Agilitystartswithtrust WouldyoutrustanAItobeyoureyes?(Ep.437) FeaturedonMeta HowmighttheStagingGround&thenewAskWizardworkontheStackExchange... Overhaulingourcommunity'sclosurereasonsandguidance Linked 9 Gettingabsolutepathwithoutresolvingsymlinksinpython 0 HowcanIfindfullpathforafile? -1 Findafilebaseonknowinglatterpartofapath 3467 HowdoIlistallfilesofadirectory? 361 RelativepathsinPython 192 os.makedirsdoesn'tunderstand"~"inmypath 29 Howtoresolverelativepathsinpython? 30 Howtogetonlyfilesindirectory? 13 Pythoncantgetfullpathnameoffile 4 Python-Anywaytoturnrelativepathsintoabsolutepaths? Seemorelinkedquestions Related 6607 HowdoIcheckwhetherafileexistswithoutexceptions? 6741 WhataremetaclassesinPython? 3288 Howtocopyfiles? 5164 HowcanIsafelycreateanesteddirectory? 791 Importamodulefromarelativepath 7251 DoesPythonhaveaternaryconditionaloperator? 3523 HowdoIgetthecurrenttime? 1234 HowdoIgetthefullpathofthecurrentfile'sdirectory? 1303 Relativeimportsforthebillionthtime HotNetworkQuestions Ifamanisraped,resultinginpregnancy,andthewomanchoosestocarrythechildtoterm,isthemanstillresponsibleforchildsupport? Wherearehistoricalresearchpapersstored? HowdidJesusgrowinfavorwithGod?Luke2:52 Arethereaeromedicalreasonstoavoidtoo-rapiddescentinhypoxia? Tabularray:correctrownumberinginlongtblr WhydophysicalistsusetheTuringMachineasamodelofthebrain? Doduplicatesofthe"Groupinput"onGeometryNodeswastememory? SumofreciprocalsofSophieGermainprimes Novelinwhichafemalephysicistcreatesamini-universe Wheretostartfirstinfinishingmybasement HowtohavetheleasthasslebeatingaButterfree? HowcanIapplyafunctiononlytoeven-indexelementsofalist? 90svampireshortstorysetinpost-communistRomaniahavingasubplotabouttheeffectsofAIDSonvampires WasthereacompressionprogrambasedontheMayne-Jamesalgorithm? DensityofMultivariateNormalDistribution(MVN):Dimension=1ork? TriggeringgenerictransistorswithUVorgreenlight? Drawthesesquareswithtext Asanevaluatorinmathematics,howshouldIgraderesponsesthatanswerthequestionasked,butinlessdetailthandesired? Knowingthetwoquantitiesof'est' Bestwaytocleanupnailsafterdemolition? Timetravelshortstoryaboutamanfromamulti-racialfuturewhoiskilledwhenhegoesbacktoaracistpast? Whydomodernoperatingsystems*ever*haveperceptibleinput(keyboard/mouse)lag? Grammarlyeditingmyeffects,shouldIkeepthemorlistentoGrammerly? Whyissignedandunsignedadditionconverteddifferentlyfor16and32bitintegers? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-py Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings
延伸文章資訊
- 1How to get an absolute file path in Python - Stack Overflow
Given a path such as "mydir/myfile.txt" , how do I find the file's absolute path relative to the ...
- 2os.path.abspath: How to Get Absolute Path in Python
The os.path.abspath() is a built-in Python function that returns a normalized absolute version of...
- 3在Python 中獲取絕對路徑
要使用 pathlib 獲得絕對路徑,需要從 pathlib 模組中匯入 Path 類,並使用該類的 Path.absolute() 函式來確定給定檔案或資料夾的絕對路徑。 Python.
- 4Get the path of running file (.py) in Python - nkmk note
Use os.path.basename() , os.path.dirname() to get the file name and the directory name of the run...
- 5Python Program to Get the Full Path of the Current Working ...
Example 1: Using pathlib module · Pass the file's name in Path() method. · parent gives the logic...