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

PythonPath

Python Problem Overview


UNIX absolute path starts with '/', whereas Windows starts with alphabet 'C:' or '\'. Does python have a standard function to check if a path is absolute or relative?

Python Solutions


Solution 1 - Python

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)

Solution 2 - Python

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('.')

Solution 3 - Python

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:/')

Solution 4 - Python

Solution 5 - Python

import os.path

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

os.path.isabs('user')
False

Solution 6 - Python

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

Solution 7 - Python

another way if you are not in current working directory, kinda dirty but it works for me.

import re
path = 'my/relative/path'
# path = '..my/relative/path'
# path = './my/relative/path'

pattern = r'([a-zA-Z0-9]|[.])+/'
is_ralative = bool(pattern)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionprosseekView Question on Stackoverflow
Solution 1 - PythonDonald MinerView Answer on Stackoverflow
Solution 2 - PythonWayne WernerView Answer on Stackoverflow
Solution 3 - PythonPraveenView Answer on Stackoverflow
Solution 4 - PythonkennytmView Answer on Stackoverflow
Solution 5 - PythonAlex BliskovskyView Answer on Stackoverflow
Solution 6 - PythonShohamView Answer on Stackoverflow
Solution 7 - PythonMahendraView Answer on Stackoverflow