note.nkmk.me

Get and change the current working directory in Python

Posted: 2019-09-16 / Tags: Python, File

With 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: os.getcwd()
  • Change the current working direcory: os.chdir()

The path of the script file (.py) being executed can be obtained with __file__. See the following post.

Sponsored Link

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 str.

You can check the result with print().

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: os.chdir()

You can change the current working directory with os.chdir().

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 cd command.

os.chdir('../')

print(os.getcwd())
# /Users/mbp/Documents/my-project/python-snippets

chdir stands for "change directory". Same as cd.

With the __file__ and os.path functions, you can change the current directory to the directory where the running script file (.py) exists.

os.chdir(os.path.dirname(os.path.abspath(__file__)))
source: file_path.py

See the following post for details.

Sponsored Link
Share

Related Categories

Related Posts