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

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
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!