How do I change the working directory in Python?

In the shell, we use cd to change directories. What’s the Python equivalent of changing the current working directory during script execution?

I’m trying to understand how Python’s change directory works using the standard library.

In Python, the equivalent of cd is os.chdir(). I use it a lot when my script needs to move around the file system. For example:

import os
os.chdir('/path/to/folder')

Once you run that, any file operations happen relative to that new path. Just don’t forget to import os first! It’s been super handy for organizing output files into specific directories during automation.

Thanks @shilpa.chandel, I use os.chdir() too, but I make it a habit to double-check that the change actually happened using os.getcwd().

Here’s what I usually do:

import os

print("Before:", os.getcwd())
os.chdir('/my/new/folder')
print("After:", os.getcwd())

This saved me once when I was passing a relative path, and it silently failed due to a typo.

Now I always confirm the path switch.

I recently started using pathlib and found that starting with Python 3.11, you can do:

from pathlib import Path
Path('/some/path').chdir()

It’s cleaner and feels more modern than os.chdir(). If you’re already using pathlib for file manipulation, this fits in nicely and keeps everything consistent.