Get and change (move) the current directory in Python

Money and Business

This section explains how to get, check, and change (move) the working directory (current directory) where Python is running.

Use the os module. It is included in the standard library, so no additional installation is required.

Acquisition and modification will be explained respectively.

  • Get and check the current directory:os.getcwd()
  • Change (move) the current directory:os.chdir()

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

Get and check the current directory: os.getcwd()

os.getcwd()
This will return the absolute path of the working directory (current directory) where Python is currently running as a string.

You can check it by outputting it with print().

import os

path = os.getcwd()

print(path)
# /Users/mbp/Documents/my-project/python-snippets/notebook

print(type(path))
# <class 'str'>

getcwd is an abbreviation for

  • get current working directory

By the way, the UNIX pwd command stands for the following.

  • print working directory

It is convenient to use os.path to handle path strings.

Change (move) the current directory: os.chdir()

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

Specify the path to move to as an argument. Either absolute or relative path can be used to move to the next level.

  • '../'
  • '..'

You can move and 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 is an abbreviation for the following, and is the same as cd.

  • change directory

To move to the directory where the script file (.py) you are executing is located, use the following function.

  • __file__
  • os.path
os.chdir(os.path.dirname(os.path.abspath(__file__)))
Copied title and URL