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()

print(current_working_directory)
Output:

/Users/code2care/Desktop

Get Current Working Directory using Python
Example 2:
import os
present_working_directory=os.system("pwd")
print(present_working_directory)

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())
/Users/code2care/Desktop



Using pathlib module

Example 4:
from pathlib import Path

path = Path.cwd();

print(path)
Output:

/Users/code2care/Documents


Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org



















Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap