Python os.path module provides different important functions on pathnames. This module is inside python os module. This is an inbuilt module in python and we can use all of its methods without installing any other third party lib.
Even though os.path module provides different pathname functions and it makes our life easier, make sure to match the python version of your local system and your production server. Some functions are available only on some specific python versions.
To find the absolute path of a file, we can use the abspath() method defined in os.path submodule. It takes one path as the parameter and returns the normalized absolute version of the given path. Starting from python 3.6, it can also take a path-like object.
os.path.abspath method is defined as below:
Let’s start with a simple example:
import os print(os.path.abspath('hello.txt'))
It will print the absolute path of the file hello.txt and print one output as like below:
We can also change the current directory to a different directory and get the absolute path for that directory. For example:
import os os.chdir('/Downloads/NewFolder') print(os.path.abspath('hello.txt'))
It will first change the directory by using chdir and then find the absolute path of the file for that directory.
Make sure that the directory exists. Otherwise, it will throw one FileNotFoundError.
- Python program to check if a path exists
- Python os.path.lexists() method explanation with example
- How to check if a path is file or directory in Python
- How to get the last access time of a path in python
- Python program to get the last modified time of a path
- How to find the common path in a list of paths in python