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
-
Have Questions? Post them here!
More Posts related to Python,
- Check version of pip package installer for Python
- How to install Python 3.9 using brew on Mac
- Python Program To Calculate Simple Interest (SimpleInterest.py)
- Indent Python code in Notepad++
- Change label (text) color in tkinter
- Float built-in function in Python
- [Fix] ValueError: substring not found in Python
- pip get list of all outdated Python packages
- Calculate discount amount python code
- 3 Python program to add two numbers
- How to List all Packages installed using pip [Python]
- Python range() function examples
- How to resolve Failed to create interpreter PyCharm Error
- Format Python Code in Visual Studio Code (VS Code)
- Validate email address in Python using regular expression (regex)
- Install and Run Jupyter Notebook on Mac (macOS)
- How to delete a file using Python code example
- Base64 Encoding Decoding in Python Programming
- How to pip install Python Modules in VSCode
- Change the background of Tkinter label or text
- Comments in Python Programming
- Take input argument from command line in Python Programming
- How to Convert Python String to DateTime Object
- Tkinter - add x and y padding to label text
- [Tutorial] Install Python on Visual Studio Code (VS Code)
More Posts:
- Struts 2 Hello World Example in Eclipse - Java
- Read JSON File in Python Program - Python
- Open Large File in Notepad++ (Fix: File is too big to be opened by Notepad++) - NotepadPlusPlus
- Install AWS CLI using Brew Command - AWS
- Know Bash shell version command - Bash
- Mac - Chrome Open a new window in Incognito mode - Chrome
- Perform an Empty Commit in Git without anything in Staging Area - Git
- List of Java Major Minor Version Numbers - Java