Get and change the current working directory in Python
os module, you can get and change the current working directory where Python is running.
os module is included in the standard library, so no additional installation is required.
Here, the following contents will be described.
- Get the current working direcory:
- Change the current working direcory:
The path of the script file (
.py) being executed can be obtained with
__file__. See the following post.
Get the current working direcory: os.getcwd()
os.getcwd() returns the absolute path of the working directory where Python is currently running as a string
You can check the result with
import os path = os.getcwd() print(path) # /Users/mbp/Documents/my-project/python-snippets/notebook print(type(path)) # <class 'str'>
getcwd stands for "get current working directory".
Change the current working direcory:
You can change the current working directory with
Specify the destination path in the argument. It can be absolute or relative. Use
'../' to move up.
You can change the current directory in the same way as the UNIX
os.chdir('../') print(os.getcwd()) # /Users/mbp/Documents/my-project/python-snippets
chdir stands for "change directory". Same as
os.path functions, you can change the current directory to the directory where the running script file (
See the following post for details.