Understand os.path.isabs(): Check a File Path is Absolute or not – Python Tutorial

By | December 10, 2019

When we save some data into a file, we have to check the path of this file is absolute or not. We can use os.path.isabs() to do this. In this tutorial, we will use some examples to show you how to use this function.

Syntax

os.path.isabs(path)

Check the path of the file is absolute or not.  The return value is True or False. This function works fine on windows and unix system.

When we need this function?

If you plan to write some data into a file, you should do:

1.Checking the path of this file is absolute or not

2.If the path is not, you should get the absolute path and you may have to create some directories.

To get the absolute path of file, you can refer to this tutorial:

Best Practice to Get the Absolute Path of Current Python Script – Python Tutorial

3. If the path of the file is absolute, you should check the directory path exist or not. If it is not existing, you should create it.

Best Practice to Python Create Directory Recursively – Python Tutorial

How to use os.path.isabs()

Here is an example:

import os

path = 'C:\\'
print(os.path.isabs(path))
path = 'C:\\1.txt'
print(os.path.isabs(path))

All results are:True

path = './1.txt'
print(os.path.isabs(path))

The result is: False

Leave a Reply