How to Get and Change the Current Working Directory in Python

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

To find the current working directory in Python, use os.getcwd(), and to change the current working directory, use os.chdir(path). HowtoGetandChangetheCurrentWorkingDirectoryinPythonUpdated  Aug10,2021•3minreadContentsGettingtheCurrentWorkingDirectoryinPythonChangingtheCurrentWorkingDirectoryinPythonConclusionShare:WhendealingwithfilesindirectoriesinPython,itisalwaysagoodideatouseabsolutepaths.However,ifyouareworkingwithrelativepaths,you’llneedtounderstandtheconceptofthecurrentworkingdirectoryandhowtofindorchangethecurrentworkingdirectory.Anabsolutepathspecifiesafileordirectorylocationstartingfromtherootdirectory,whiletherelativepathbeginsfromthecurrentworkingdirectory.WhenyourunaPythonscript,thecurrentworkingdirectoryissettothedirectoryfromwhichthescriptisexecuted.Theospythonmoduleprovidesaportablewaytointeractwiththeoperatingsystem.ThemoduleispartofthestandardPythonlibraryandincludesmethodsforfindingandchangingthecurrentworkingdirectory.GettingtheCurrentWorkingDirectoryinPython#Thegetcwd()methodoftheosmoduleinPythonreturnsastringthatcontainstheabsolutepathofthecurrentworkingdirectory.Thereturnedstringdoesnotincludethetrailingslashcharacter.os.getcwd() Tousetheosmodulemethods,youmustimportthemoduleatthetopofthefile.Belowisanexampleshowinghowtoprintthecurrentworkingdirectory:#Importtheosmodule importos #Getthecurrentworkingdirectory cwd=os.getcwd() #Printthecurrentworkingdirectory print("Currentworkingdirectory:{0}".format(cwd)) #Printthetypeofthereturnedobject print("os.getcwd()returnsanobjectoftype:{0}".format(type(cwd))) Theoutputwilllooksomethinglikethis:Currentworkingdirectory:/home/linuxize/Desktop os.getcwd()returnsanobjectoftype: Ifyouwanttofindthedirectorywherethescriptislocated,useos.path.realpath(__file__).Itwillreturnastringcontainingtheabsolutepathtotherunningscript.ChangingtheCurrentWorkingDirectoryinPython#TochangethecurrentworkingdirectoryinPython,usethechdir()method.os.getcwd(path) Themethodacceptsoneargument,thepathtothedirectorytowhichyouwanttochange.Thepathargumentcanbeabsoluteorrelative.Hereisanexample:#Importtheosmodule importos #Printthecurrentworkingdirectory print("Currentworkingdirectory:{0}".format(os.getcwd())) #Changethecurrentworkingdirectory os.chdir('/tmp') #Printthecurrentworkingdirectory print("Currentworkingdirectory:{0}".format(os.getcwd())) Theoutputwilllooksomethinglikethis:Currentworkingdirectory:/home/linuxize/Desktop Currentworkingdirectory:/tmp Theargumentprovidedtothechdir()methodmustbeadirectory;otherwiseNotADirectoryErrorexceptionisraised.Ifthespecifieddirectorydoesn’texist,aFileNotFoundErrorexceptionisraised.Iftheuserunderwhichthescriptisrunningdoesn’thavethenecessarypermissions,aPermissionErrorexceptionisraised.#Importtheosmodule importos path='/var/www' try: os.chdir(path) print("Currentworkingdirectory:{0}".format(os.getcwd())) exceptFileNotFoundError: print("Directory:{0}doesnotexist".format(path)) exceptNotADirectoryError: print("{0}isnotadirectory".format(path)) exceptPermissionError: print("Youdonothavepermissionstochangeto{0}".format(path)) Conclusion#TofindthecurrentworkingdirectoryinPython,useos.getcwd(),andtochangethecurrentworkingdirectory,useos.chdir(path).Ifyouhaveanyquestionsorfeedback,feelfreetoleaveacomment.pythonreportthisadRelated TutorialsHowtoConvertIntegerintoStringinPythonHowtoInstallFlaskonUbuntu20.04HowtoInstallPython3.9onUbuntu20.04InstallOdoo14onCentOS8HowtoInstallOdoo14onUbuntu20.04HowtoFindtheLengthofaListinPythonPythonListreversereportthisadIfyoulikeourcontent,pleaseconsiderbuyingusacoffee.Thankyouforyoursupport!BuymeacoffeeSignuptoournewsletterandgetourlatesttutorialsandnewsstraighttoyourmailbox. SubscribeWe’llnevershareyouremailaddressorspamyou.RelatedArticlesNov25,2020HowtoConvertIntegerintoStringinPythonNov21,2020HowtoInstallFlaskonUbuntu20.04Nov15,2020HowtoInstallPython3.9onUbuntu20.04Writeacomment



請為這篇文章評分?