Multiple Ways To Get Current Working Directory In Python

If you are a programmer, you must have come across a requirement wherein you need to access the current working directory. The current working directory is the folder where your application is running from.

In this article, I’ll show you three different ways to get current working directory using Python.

Using os.getcwd

import os
w_dir = os.getcwd()
print(w_dir)

Using pathlib.Path.cwd

from pathlib import Path
work_dir = Path.cwd()
print(work_dir)

Using os.path

import os
print(os.path.dirname(os.path.normpath(__file__)))

Here the __file__ is a special Python build-in variable that contains the path to the currently running script. The os.path.dirname returns the directory name of the given path and the normpath method normalizes a path name by collapsing redundant separators.

I hope you enjoyed reading this article.

If you are interested in watching the recording of this, you can check this out on my YouTube channel here.


Similar Articles