Python
working directory
change directory
os module
programming tutorial

How do I change the working directory in Python?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

The current working directory controls how relative paths are resolved in a Python process. Changing it is easy with os.chdir, but doing so carelessly can make file operations brittle and hard to debug.

Checking and Changing the Current Directory

Python exposes the process working directory through the os module. os.getcwd() tells you where the process is currently running, and os.chdir() switches to a new location.

python
1import os
2
3print("before:", os.getcwd())
4os.chdir("/tmp")
5print("after:", os.getcwd())

After the call to os.chdir, every relative path in that process will be interpreted from the new location. That includes later file reads, writes, and subprocess calls that do not specify their own cwd.

If you are already using pathlib, you can combine it with os.chdir for more readable path construction:

python
1import os
2from pathlib import Path
3
4project_root = Path.home() / "projects" / "demo"
5os.chdir(project_root)
6
7print(Path.cwd())

Prefer Explicit Paths When Possible

Changing the working directory is sometimes appropriate in scripts, but many applications are easier to maintain when they use explicit absolute paths instead. A process-wide directory change affects every later relative-path operation, including code in imported modules.

For example, this avoids a global directory switch:

python
1from pathlib import Path
2
3project_root = Path.home() / "projects" / "demo"
4config_path = project_root / "config" / "settings.json"
5
6print(config_path.read_text())

If your goal is simply to open files under a known root, absolute paths are usually the safer design.

Temporarily Changing the Directory

Sometimes you do need a temporary change, such as running a command in a project folder. In that case, a context manager keeps the change local and restores the original directory automatically.

python
1import os
2from contextlib import contextmanager
3from pathlib import Path
4
5
6@contextmanager
7def working_directory(path):
8    previous = Path.cwd()
9    os.chdir(path)
10    try:
11        yield
12    finally:
13        os.chdir(previous)
14
15
16with working_directory(Path("/tmp")):
17    print("inside:", Path.cwd())
18
19print("outside:", Path.cwd())

This pattern is especially useful in tests and automation scripts because it prevents one step from leaking state into the next.

Working Directory Versus Script Location

A frequent misunderstanding is assuming the current working directory is always the folder containing the script. That is not guaranteed. The working directory is whatever directory the process was started from.

This difference becomes obvious in test runners, cron jobs, and editor launch tasks. Code that relies on the current directory can seem correct on your machine, then fail later because another tool started the same script from a different folder.

If you need the script file location, use __file__ or Path(__file__).resolve().parent rather than Path.cwd():

python
1from pathlib import Path
2
3script_dir = Path(__file__).resolve().parent
4print("script directory:", script_dir)
5print("current working directory:", Path.cwd())

Those two paths may be different, and many path bugs come from mixing them up.

Common Pitfalls

  • Calling os.chdir in a library function can break unrelated code elsewhere in the same process.
  • Assuming the working directory equals the script directory leads to missing-file errors in production.
  • Using relative paths after several directory changes makes debugging much harder.
  • Forgetting to restore the original directory can make later steps fail unpredictably.
  • Changing directories in one thread affects the whole process, not just that thread.

Summary

  • Use os.getcwd() to inspect the current directory and os.chdir() to change it.
  • Prefer absolute paths when you want predictable file access.
  • Use a context manager if the directory change should be temporary.
  • Distinguish carefully between the current working directory and the script location.
  • Treat process-wide directory changes as shared state that can affect every later path operation.

Course illustration
Course illustration

All Rights Reserved.