How to change the current working directory in Python using os.chdir()?

Published on Aug. 22, 2023, 12:17 p.m.

You can use the os.chdir() method in Python to change the current working directory. Here’s an example code snippet that shows how to change the working directory:

import os

# get current working directory
current_dir = os.getcwd()
print("Current working directory:", current_dir)

# change working directory
os.chdir('/path/to/new/directory')

# get new working directory
new_dir = os.getcwd()
print("New working directory:", new_dir)

This code first gets the current working directory using os.getcwd(), then changes the working directory using os.chdir('/path/to/new/directory'), and finally prints out the new working directory using os.getcwd() again.

Note that the path to the new directory must be a string variable containing the path to the desired directory. If the specified directory does not exist, Python will raise a FileNotFoundError. So, make sure that the directory exists before trying to change the directory.

Tags:

os