os.path.abspath: How to Get Absolute Path in Python

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

The os.path.abspath() is a built-in Python function that returns a normalized absolute version of the pathname, which means the abspath() ... AppDividend LatestCodeTutorials HomePythonos.path.abspath:HowtoGetAbsolutePathinPython Python os.path.abspath:HowtoGetAbsolutePathinPython ByKrunal LastupdatedMar15,2022 0 The os.pathisabuilt-inPythonmodulethatprovidesarangeofusefulfunctionstochangefilesanddirectories.Thesemethodsareusedforvariouspurposes,suchasmerging,normalizing,andretrievingpathnames.Thepathparametersareeitherstringsorbytes. Python’snativeos.listdir()andos.pathfunctionsareprettylow-level.Iteratingthroughadirectoryrequiresyourprogramtocongregatefilepathsmanually.Let’sdeepdiveintooslibraryandseeitspath.abspath()function. Pythonos.path.abspath Theos.path.abspath()isabuilt-inPythonfunctionthatreturnsanormalizedabsoluteversionofthepathname,whichmeanstheabspath()functionreturnsthepathnametoapathpassedasaparameter. Syntax os.path.abspath(path) Parameters Theos.path.abspath()takesapathorfilenameasaparameterrepresentingafilesystempath. ReturnValue Theabspath()methodreturnsanormalizedversionofthepathnamepath. Example Toworkwithpathfunctions,importosmodule.Thendefineapathorfilenameandpassthattotheabspath()function,anditreturnsthenormalizedpath. importos path="Netflix.csv" file_name=os.path.abspath(path) print(file_name) Output /Users/krunal/Desktop/code/pyt/database/Netflix.csv Asyoucanseefromtheoutput,Ihavepassedafilenamefrommycurrentdirectory,whichisadatabase,anditreturnsanabsolutepathtothatdirectoryandthenthefilename. Afterchangingthecurrentdirectory TochangethecurrentdirectoryinPython,usetheos.chdir()method. importos path="Pro.R" os.chdir("/Users/krunal/Desktop/code/R") file_name=os.path.abspath(path) print(file_name) Output /Users/krunal/Desktop/code/R/Pro.R Theos.path.abspath()functionremovesthingslike.and..fromthepathgivingafullpathfromtherootofthedirectorytreetothenamedfile(orsymlink). Thatisitforos.path.abspath()functioninPython. Seealso Pythonos.path.exists() Pythonos.path.join() Pythonos.system() Pythonos.walk() Krunal 1158posts 205comments KrunalLathiyaisanInformationTechnologyEngineer.Byprofession,heisawebdeveloperwithknowledgeofmultipleback-endplatforms(e.g.,PHP,Node.js,Python)andfrontendJavaScriptframeworks(e.g.,Angular,React,andVue). PrevPost HowtoRemoveFirstElementfromArrayinJavaScript NextPost HowtoTransposeMatrixinPython reportthisad LeaveAReplyCancelReplyYouremailaddresswillnotbepublished. Savemyname,email,andwebsiteinthisbrowserforthenexttimeIcomment. Δ ThissiteusesAkismettoreducespam.Learnhowyourcommentdataisprocessed. reportthisadCategories Angular AWS Blockchain C++ CloudComputing Dart Flutter Go Java Javascript Laravel MachineLearning MicrosoftAzure MongoDB Node.js PHP Python ReactNative React.js SQL Tableau Tools TypeScript VueJS reportthisad xx



請為這篇文章評分?