Python program to get the absolute path of a file

Python os.path module:

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.

Finding the absolute path of a file:

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.

Definition of os.path.abspath():

os.path.abspath method is defined as below:

os.path.abspath(path)

Example of os.path.abspath:

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:

/Users/cvc/hello.txt

Get the absolute path by changing directory:

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.

You might also like: