Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a path is absolute path or relative path in a cross-platform way with Python?

Tags:

python

path

People also ask

How do you know if a path is absolute or relative in Python?

path. isabs() method in Python is used to check whether the specified path is an absolute path or not. On Unix platforms, an absolute path begins with a forward slash ('/') and on Windows it begins with a backward slash ('\') after removing any potential drive letter.

How can you tell if a path is relative or absolute?

In simple words, an absolute path refers to the same location in a file system relative to the root directory, whereas a relative path points to a specific location in a file system relative to the current directory you are working on.

How do you distinguish the following two paths relative and absolute?

An absolute path is defined as specifying the location of a file or directory from the root directory(/). In other words,we can say that an absolute path is a complete path from start of actual file system from / directory. Relative path is defined as the path related to the present working directly(pwd).


os.path.isabs returns True if the path is absolute, False if not. The documentation says it works in windows (I can confirm it works in Linux personally).

os.path.isabs(my_path)

And if what you really want is the absolute path, don't bother checking to see if it is, just get the abspath:

import os

print os.path.abspath('.')

From python 3.4 pathlib is available.

In [1]: from pathlib import Path

In [2]: Path('..').is_absolute()
Out[2]: False

In [3]: Path('C:/').is_absolute()
Out[3]: True

In [4]: Path('..').resolve()
Out[4]: WindowsPath('C:/the/complete/path')

In [5]: Path('C:/').resolve()
Out[5]: WindowsPath('C:/')

Use os.path.isabs.


import os.path

os.path.isabs('/home/user')
True

os.path.isabs('user')
False

Actually I think none of the above answers addressed the real issue: cross-platform paths. What os.path does is load the OS dependent version of 'path' library. so the solution is to explicitly load the relevant (OS) path library:

import ntpath
import posixpath

ntpath.isabs("Z:/a/b/c../../H/I/J.txt")
    True
posixpath.isabs("Z:/a/b/c../../H/I/J.txt")
    False