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
-
Facing issues? Have Questions? Post them here! I am happy to answer!
More Posts related to Python,
- Python: Convert Date to DateTime
- How to sort a List using Lambda in Python
- Python matplotlib segmentation fault: 11 macOS Big Sur
- What is Terminal Velocity and its Formula? How to calculate it programmatically?
- How to install Python 3.11 on Mac
- How to flatten a nested list in Python
- Python: Pandas Merge DataFrames on Index Example
- How to Run all Cells at Once Jupyter Notebook
- Python - Convert float to String
- How to add borders to tkinter label text
- How to Exit a Loop in Python Code
- [Python] Fix: ValueError: All arrays must be of the same length
- Sorting an array using Bubble Sort in Python Programming
- How to Unzip a file using Python
- Python: Merge DataFrames Pandas Outer Join Example
- Change label (text) color in tkinter
- Convert Float to String in Python
- Fix: fatal error: No such file or directory compilation terminated
- Python: Access index/counter of a for loop iteration
- Import Other Python Files Examples
- How to install Anaconda on Mac (M1/M2 Mac)
- Python Regular Expression to Find All Matches in List
- How to Read a binary File with Python
- How to disable warnings while Python file execution
- Know current Python Version
More Posts:
- Best way to Convert Primitive long to int in Java with some Cautions - Java
- Android Disable EditText from Auto Focus on Activity load - Android
- How to force quit or kill Notepad++ Process - NotepadPlusPlus
- How to show Videos on SharePoint Page - SharePoint
- [fix] docker exec requires at least 2 arguments - Docker
- How to check of Updates on Microsoft Edge Browser on Mac (macOS) - MacOS
- Java JDBC NumberFormatException: For input string - Java
- Change Home Page on Safari for Mac (macOS) - MacOS