
Absolute paths should always be used when working with files in directories in Python. If you’re dealing with relative paths, though, you’ll need to know what the current working directory is and how to locate or modify it. A relative path starts from the current working directory, but an absolute route starts from the root directory.
The os
python module allows you to interact with the operating system from anywhere. The module is part of the Python standard library and offers methods for locating and modifying the current working directory.
What is an Absolute path?
An absolute path is defined as the specifying the location of a file or directory from the root directory (/). In other words we can say absolute path is a complete path from start of actual filesystem from / directory.
Get the Current Working Directory in Python
1. Using getcwd() module in Python to get Current Working Directory
The os module’s getcwd()
function returns a string with the absolute path to the current working directory.
os.getcwd()
You must import the os module at the top of the program to use its methods.
Python code to obtain the current directory:
import os path = os.getcwd() print(path)
2. Using chdir() module to get Current Working Directory
To change the current directory, we utilize the os module’s chdir()
methods, which are similar to the os.getcwd
function in Python.
Python code to change the current directory:
import os os.chdir("/home/ph0enix/Desktop") path = os.getcwd() print(path)
3. Using pathlib module to get Current Working Directory
Using the pathlib module, create a python script using the following code to read and fetch the current working directory. The Path class’s cwd()
function is used to fetch the current working directory where the script is running.
from pathlib import Path current_path = Path.cwd() print(current_path)
4. Using realpath() module to Get Current Working Directory
Another way to get the current working directory is to use the realpath()
function. Using the realpath() function, create a python file with the following script to output the current working directory with the script name.
The __file__
parameter value in the script contains the pathname of the file in which the os module is imported.
import os current_path = os.path.realpath(__file__) print(current_path)
Conclusion
This tutorial provides different examples to explain how to use pathlib and os modules to read the current working directory. This tutorial also shows how to obtain the current working directory after updating it with user input.
Feel free to leave a comment if you have any questions or feedback.