How to Get and Change the Current Working Directory in Python
文章推薦指數: 80 %
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:
延伸文章資訊
- 1Python : How to Get the current working directory - thisPointer
It returns a string containing the current working directory. For calling this function we need t...
- 2Find the current directory and file's directory - python - Stack ...
To get the current directory full path >>import os >>print os.getcwd(). Output: "C :\Users\admin\...
- 3Python get the current directory - Flexiple Tutorials
Python get current directory: ... To return the directory you are currently in, we use the OS mod...
- 4os .pwd() Code Example - Grepper
import os path = os.getcwd() print(path) # /Users/mbp/Documents/my-project/python-snippets/notebo...
- 5Get and change the current working directory in Python
os.getcwd() returns the absolute path of the working directory where Python is currently running ...