Examples
- How to Create Directory in Python? New and If Not Exists
- How to Change Directory in Python? Change Current Working Directory
- How to Get Current Working Directory in Python?
- How to Remove Directory in Python? (Empty & With Files)
- How to Copy Directory in Python? Program With Examples
- How to Open Directory in Python? Program & Example
- How to Read All Files in Directory in Python? (All Types of Files)
- How to Copy File in Python From One Directory to Another? (With and Without shutil)
- Python File Append Program (Append to File)
- How to Read Text File in Python Line by Line? (3 Ways)
- How to Get File Name From File Path in Python?
- Get Number of Lines in File in Python (Line Count)
- How to Get Size of File in Python? (File Size Program)
How to Get Current Working Directory in Python?
The current working directory in Python is the directory from which your script is currently running. It plays a crucial role when working with file systems, as it determines the starting point for file operations. In this post, we will understand how to get the current working directory in Python.
Python provides a straightforward way to obtain the current working directory using the os.getcwd() function. The os module offers functions for interacting with the operating system, including file system operations. With the os.getcwd() function, you can easily retrieve the current working directory as a string.
Program to Get Current Working Directory in Python
Code
import os
# Get the current working directory
current_directory = os.getcwd()
# Print the current working directory
print("Current working directory:", current_directory)
Output
Current working directory: /home/ubuntu/tutorialsfreak-node
Explanation
In this program, the os.getcwd() function is used to retrieve the current working directory. The returned value is assigned to the current_directory variable.
By executing os.getcwd(), you can obtain the current working directory as a string. You can then use it for various purposes, such as accessing files within the current working directory or performing file operations.
The program concludes by printing the current working directory using the print() function.
When you run this program, it will display the current working directory on the console. This provides you with the information necessary to work with files and directories within your Python script.