How to Get and Change the Current Working Directory in Python

By 

Updated on

5 min read

Python: Get and Change the Current Working Directory

When working with files in Python, it is always a good idea to use absolute paths. If you are working with relative paths, you will need to understand the concept of the current working directory and how to find or change it. An absolute path specifies a file or directory location starting from the root, while a relative path begins from the current working directory.

When you run a Python script, the current working directory is set to the directory from which the script is executed.

The os Python module provides a portable way to interact with the operating system. It is part of the standard Python library and includes methods for getting and changing the current working directory.

Getting the Current Working Directory in Python

The os.getcwd() method returns a string containing the absolute path of the current working directory. The returned string does not include a trailing slash.

py
os.getcwd()

To use the os module, import it at the top of your file. Here is an example that prints the current working directory:

py
import os

cwd = os.getcwd()
print(f"Current working directory: {cwd}")
print(f"os.getcwd() returns an object of type: {type(cwd)}")

The output will look something like this:

output
Current working directory: /home/linuxize/Desktop
os.getcwd() returns an object of type: <class 'str'>
Info
If you want to find the directory where the script is located, use Path(__file__).resolve().parent (or os.path.dirname(os.path.realpath(__file__))).

Changing the Current Working Directory in Python

To change the current working directory in Python, use os.chdir():

py
os.chdir(path)

The method accepts one argument, the path to the directory to change to. The path argument can be absolute or relative.

Here is an example:

py
import os

print(f"Current working directory: {os.getcwd()}")

os.chdir('/tmp')

print(f"Current working directory: {os.getcwd()}")

The output will look something like this:

output
Current working directory: /home/linuxize/Desktop
Current working directory: /tmp

The argument passed to os.chdir() must be a directory. If the path does not exist, a FileNotFoundError is raised. If the path is not a directory, NotADirectoryError is raised. If the running user does not have the necessary permissions, a PermissionError is raised.

To handle these exceptions, wrap the call in a try block:

py
import os

path = '/var/www'

try:
    os.chdir(path)
    print(f"Current working directory: {os.getcwd()}")
except FileNotFoundError:
    print(f"Directory: {path} does not exist")
except NotADirectoryError:
    print(f"{path} is not a directory")
except PermissionError:
    print(f"You do not have permissions to change to {path}")

Using pathlib

Python 3.4 introduced the pathlib module as a modern, object-oriented alternative to os for file system paths. To get the current working directory as a Path object, use Path.cwd():

py
from pathlib import Path

cwd = Path.cwd()
print(f"Current working directory: {cwd}")
output
Current working directory: /home/linuxize/Desktop

Path.cwd() returns a Path object instead of a string. Path objects support convenient operations such as joining paths with /, checking existence, and iterating over directory contents. For path existence checks, see How to Check if a File or Directory Exists in Python .

pathlib does not provide a chdir() method. To change the current directory while still using Path objects, pass a Path instance to os.chdir():

py
import os
from pathlib import Path

target_dir = Path('/tmp')
os.chdir(target_dir)
print(f"Current working directory: {Path.cwd()}")

This keeps path handling in pathlib while using the correct API for changing the process working directory.

Quick Reference

Taskos modulepathlib
Get current directoryos.getcwd()Path.cwd()
Change current directoryos.chdir(path)os.chdir(Path(path))

Troubleshooting

FileNotFoundError when calling os.chdir()
The directory does not exist. Verify the path is correct before calling chdir(), or use a try/except block to handle the error gracefully.

NotADirectoryError when calling os.chdir()
The path you provided points to a file, not a directory. Pass a directory path to os.chdir().

PermissionError when calling os.chdir()
The current user does not have execute permission on the target directory. Run the script with appropriate permissions or adjust the directory permissions.

FAQ

What is the difference between the script directory and the current working directory?
The current working directory is the directory from which the script is launched. The script directory is where the script file is saved. They are often different. Use os.getcwd() for the working directory and os.path.dirname(os.path.realpath(__file__)) for the script’s location.

Does os.chdir() affect the parent process?
No. Changing the working directory inside a Python script only affects that process. The shell or process that launched the script is not affected.

Should I use os or pathlib for working with paths?
For new code targeting Python 3.4+, pathlib is generally preferred because it provides an object-oriented interface that is easier to read and compose. Use os.chdir() when you need to change the working directory.

Why does os.getcwd() return a different path than expected?
The current working directory depends on where you launched the script, not where the script file is saved. Print os.getcwd() at the start of your script to confirm the actual working directory.

Can I use a relative path with os.chdir()?
Yes. For example, os.chdir('..') moves up one directory level. Relative paths are resolved from the current working directory at the time of the call.

Conclusion

Use os.getcwd() to get the current working directory and os.chdir(path) to change it. For new projects, pathlib.Path.cwd() is the modern alternative for getting the working directory.

Tags

Linuxize Weekly Newsletter

A quick weekly roundup of new tutorials, news, and tips.

About the authors

Dejan Panovski

Dejan Panovski

Dejan Panovski is the founder of Linuxize, an RHCSA-certified Linux system administrator and DevOps engineer based in Skopje, Macedonia. Author of 800+ Linux tutorials with 20+ years of experience turning complex Linux tasks into clear, reliable guides.

View author page