e Learning

How to Get Current Directory in Python

Python’s os module has a getcwd() function, which we can use to get the current working directory in a python script or console.

In the Python interpreter, first import the os module and then run the os.getcwd() command.

import os

The output will be the absolute pathname of the current working directory.

python get current directory

The os module provides a platform-independent way to interact with your computer operating system. We can use getcwd() in a python script to print the working directory.

from os import getcwd

current_directory = getcwd()
print("currently working on: " + current_directory)

In the preceding example, we assigned the current working directory to the current_directory variable and then print the variable in the next line.

python print working directory

Just like that, we can use the getcwd() function to get the current directory in any operating system, including Linux, Microsoft Windows, and macOS. This is very helpful, especially for sysadmins, when writing scripts with Python.