Why would one use both, os.path.abspath and os.path.realpath?

文章推薦指數: 80 %
投票人數:10人

In the layman terms, if you are trying to get the path of a shortcut file, absolute path gives the ... Home Public Questions Tags Users Companies Collectives ExploreCollectives Teams StackOverflowforTeams –Startcollaboratingandsharingorganizationalknowledge. CreateafreeTeam WhyTeams? Teams CreatefreeTeam CollectivesonStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. Learnmore Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. Learnmore Whywouldoneuseboth,os.path.abspathandos.path.realpath? AskQuestion Asked 5years,10monthsago Modified 3yearsago Viewed 70ktimes 128 32 Inmultipleopensourceprojects,Ihaveseenpeopledoos.path.abspath(os.path.realpath(__file__))togettheabsolutepathtothecurrentfile. However,Ifindthatos.path.abspath(__file__)andos.path.realpath(__file__)producethesameresult.os.path.abspath(os.path.realpath(__file__))seemstobeabitredundant. Isthereareasonpeopleareusingthat? python Share Improvethisquestion Follow editedJun1,2018at6:48 Trilarion 9,85199goldbadges6060silverbadges9898bronzebadges askedJun16,2016at15:30 hchhch 5,31088goldbadges1919silverbadges2424bronzebadges Addacomment  |  3Answers 3 Sortedby: Resettodefault Highestscore(default) Datemodified(newestfirst) Datecreated(oldestfirst) 147 Foryourstatedscenario,thereisnoreasontocombinerealpathandabspath,sinceos.path.realpathactuallycallsos.path.abspathbeforereturningaresult(IcheckedPython2.5toPython3.6). os.path.abspathreturnstheabsolutepath,butdoesNOTresolvesymlinksinitsargument. os.path.realpathwillfirstresolveanysymboliclinksinthepath,andthenreturntheabsolutepath. However,ifyouexpectyourpathtocontaina~,neitherabspathorrealpathwillresolve~totheuser'shomedirectory,andtheresultingpathwillbeinvalid.Youwillneedtouseos.path.expandusertoresolvethistotheuser'sdirectory. Forthesakeofathoroughexplanation,herearesomeresultswhichI'veverifiedinWindowsandLinux,inPython3.4andPython2.6.Thecurrentdirectory(./)ismyhomedirectory,whichlookslikethis: myhome |-data(symlinkto/mnt/data) |-subdir(extradirectory,forverboseexplanation) #os.path.abspathreturnstheabsolutepath,butdoesNOTresolvesymlinksinitsargument os.path.abspath('./') '/home/myhome' os.path.abspath('./subdir/../data') '/home/myhome/data' #os.path.realpathwillresolvesymlinksANDreturnanabsolutepathfromarelativepath os.path.realpath('./') '/home/myhome' os.path.realpath('./subdir/../') '/home/myhome' os.path.realpath('./subdir/../data') '/mnt/data' #NEITHERabspathorrealpathwillresolveorremove~. os.path.abspath('~/data') '/home/myhome/~/data' os.path.realpath('~/data') '/home/myhome/~/data' #Andthereturnedpathwillbeinvalid os.path.exists(os.path.abspath('~/data')) False os.path.exists(os.path.realpath('~/data')) False #Userealpath+expandusertoresolve~ os.path.realpath(os.path.expanduser('~/subdir/../data')) '/mnt/data' Share Improvethisanswer Follow editedApr12,2019at23:32 MarcH 17.4k11goldbadge2727silverbadges2424bronzebadges answeredOct28,2016at18:29 jobradjobrad 1,58122goldbadges99silverbadges77bronzebadges 2 3 Nice.Tomakeyourpointyourlastexampleshouldbeos.path.realpath(os.path.expanduser('~/subdir/../data')) – Arthur Apr7,2018at16:13 4 Thenalsodonotforgetaboutos.path.expandvarsifvariablesareusedinapath – Slavenskij Apr11,2018at6:55 Addacomment  |  82 os.path.realpathderefencessymboliclinksonthoseoperatingsystemswhichsupportthem. os.path.abspathsimplyremovesthingslike.and..fromthepathgivingafullpathfromtherootofthedirectorytreetothenamedfile(orsymlink) Forexample,onUbuntu $ls-l total0 -rw-rw-r--1guestguest0Jun1608:36a lrwxrwxrwx1guestguest1Jun1608:36b->a $python Python2.7.11(default,Dec152015,16:46:19) [GCC4.8.4]onlinux2 Type"help","copyright","credits"or"license"formoreinformation. >>>fromos.pathimportabspath,realpath >>>abspath('b') '/home/guest/play/paths/b' >>>realpath('b') '/home/guest/play/paths/a' Symlinkscancontainrelativepaths,hencetheneedtouseboth.Theinnercalltorealpathmightreturnapathwithembedded..parts,whichabspaththenremoves. Share Improvethisanswer Follow editedMar24,2017at4:59 MartinTournoij 24.9k2424goldbadges101101silverbadges136136bronzebadges answeredJun16,2016at15:36 kdopenkdopen 7,82777goldbadges4141silverbadges5050bronzebadges 3 12 Whilethisanswerdescribesthedifferencebetweenthetwofunctions,itisn'ttruethattheresultofrealpath()cancontain..componentsanddoesn'treallyanswerthequestionofwhyyouwoulduseboth;jobrad'sanswerismoreaccurate. – Miles Mar24,2017at3:41 ForPython3.7andwindows,realpathdon'tunderstandsubsteddrivesSoforasubsteddrivesayP:\,havingthesourcefolderc:\MyFolder\Bla,realpathreturnsP:\notc:\MyFolder\Bla.Anyoneknowinghowtogetthe"real"path? – TotteKarlsson Feb17,2019at0:34 Forme,abspathstillfollowedsymlinksifthecurrentdirectoryisasymlink.Ionlyfoundthisanswerstackoverflow.com/questions/54665065/…tostopthisbehavior. – VictorSergienko May3,2020at2:01 Addacomment  |  10 Inthelaymanterms,ifyouaretryingtogetthepathofashortcutfile,absolutepathgivesthecompletepathofthefilepresentintheshortcutlocation,whilerealpathgivestheoriginallocationpathofthefile. Absolutepath,os.path.abspath(),givesthecompletepathofthefilewhichislocatedinthecurrentworkingdirectoryorthedirectoryyoumentioned. Realpath,os.path.realpath(),givesthecompletepathofthefilewhichisbeingreferred. Eg: file="shortcut_folder/filename" os.path.abspath(file)="C:/Desktop/shortcut_folder/filename" os.path.realpath(file)="D:/PyCharmProjects/Python1stClass/filename" Share Improvethisanswer Follow answeredOct24,2017at14:06 ExtractTable.comExtractTable.com 70299silverbadges1919bronzebadges Addacomment  |  YourAnswer ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggedpythonoraskyourownquestion. TheOverflowBlog Agilitystartswithtrust WouldyoutrustanAItobeyoureyes?(Ep.437) FeaturedonMeta HowmighttheStagingGround&thenewAskWizardworkontheStackExchange... Shouldweburninatethe[qa]tag? Overhaulingourcommunity'sclosurereasonsandguidance Linked 1 os.path.dirname(__file__)vsos.path.dirname(os.path.abspath(__file__))what'sthedifference? 2 Howtogetabsolutepathonlinuxwhenrunningfromanotherlocation 3 Python:getcwdandpwdifdirectoryisasymboliclinkgivedifferentresults 0 Differencebetweenopen(filepath)andopen(os.path.abspath(filepath)) 0 takingabspathfromosmodule 0 Retrievethepathofanopenedfile Related 1976 Whyisitstring.join(list)insteadoflist.join(string)? 3362 Whatisthedifferencebetween__str__and__repr__? 888 Runningunittestwithtypicaltestdirectorystructure 659 Pythonprogressionpath-Fromapprenticetoguru 3059 HowdoIclonealistsothatitdoesn'tchangeunexpectedlyafterassignment? 2073 HowdoIprintcurly-bracecharactersinastringwhileusing.format? HotNetworkQuestions What's"Q"intheairlineIATAcodes? AnexampleofPapañca? HowdoIfindtheLaurentseriesexpansionforthiscomplexfunction? Howdoesonedeterminetheboundaryofanobject? CanyoucarrysomeoneusingLevitatelikeaballoon? DensityofMultivariateNormalDistribution(MVN):Dimension=1ork? DuallicensingAGPL3.0/EUPL1.2 Sailinganage-of-sailsloopwith2-mancrew BJT:definitionof"edgeofsaturation" InoneofHeinlein'slesser-knownnovels,hedescribedanunusualabilitytodetectmetalobjectswithoutlookingatthem.Whichone? Wherearehistoricalresearchpapersstored? Arethereaeromedicalreasonstoavoidtoo-rapiddescentinhypoxia? VectorsperpendiculartoaBeziercurvepath Isresponsibilityforachildbasedongenetics? CollatzEncoding Whywouldthedevilgivesomeoneimmortalityinexchangeforthemmaintainingadiary? HowdoIchangethesnappingtogglefromCTRLtosomeotherkey? Asanevaluatorinmathematics,howshouldIgraderesponsesthatanswerthequestionasked,butinlessdetailthandesired? IsSchedule80PVCpiperecommended/commonlyusedforwatermainconnections? Whyisn'ttheRamachandranplotsymmetric? HowcanIapplyafunctiononlytoeven-indexelementsofalist? Moviewherethecharactersfindsoutwhattheyhavetodorightatthemomenttheyneedtodoittoavoidtheenemyknowingtheirplan HarmonicfunctionsoncompleteRiemannianmanifolds Reportpowerifresultisstatisticallysignificant morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-py Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?