How to check if a path is absolute path or relative path in a cross-platform way with Python?
PythonPathPython 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
Use os.path.isabs
.
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)