Python: How to get Current Directory

Working with files in Python Programming is a common scenario, there are various packages that you can make use of in order to get the current directory, but the most widely used one is the os module.

Using os module

To get the current working directory make use of os.getcwd() method from the os module.

Example 1:
import os

current_working_directory = os.getcwd()



Get Current Working Directory using Python
Example 2:
import os

Example 3: Using Terminal
% python3
Python 3.10.8 (main, Oct 21 2022, 22:22:30) [Clang 14.0.0 (clang-1400.0.29.202)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> os.getcwd()
Traceback (most recent call last):
  File "<stdin>", line 1, in 
NameError: name 'os' is not defined
>>> import os
>>> print(os.getcwd())

Using pathlib module

Example 4:
from pathlib import Path

path = Path.cwd();




Have Questions? Post them here!

Top Hashtags: