How can I get the current working directory in Python?
Alex K
alex k profile pic

In Python, you can get the current working directory (CWD) using theos module or thepathlib module. Here's a detailed explanation of both methods: Using the os module: Theos module provides a function calledgetcwd() that returns the current working directory as a string.

1
2
3
4
5
6

import os

current_directory = os.getcwd()

print(current_directory)

In this example,os.getcwd() retrieves the current working directory and assigns it to the variablecurrent_directory. Theprint() statement then displays the current working directory. Using the pathlib module: Thepathlib module introduced in Python 3 provides an object-oriented approach to working with file paths. ThePath class has a static method calledcwd() that returns aPath object representing the current working directory.

1
2
3
4
5
6

from pathlib import Path

current_directory = Path.cwd()

print(current_directory)

In this example,Path.cwd() returns aPath object representing the current working directory, which is assigned to the variablecurrent_directory. Theprint() statement displays the current working directory. Both methods provide the same result, allowing you to access the current working directory. Thepathlib approach is more versatile as it offers additional file path manipulation capabilities. It's recommended to use thepathlib module for more advanced file path operations. The current working directory is the default directory where Python looks for files and writes output unless you specify a different directory. Understanding and retrieving the current working directory is useful when working with file and directory operations in your Python programs.