如何使用Python以跨平台方式检查路径是绝对路径还是相对路径?

问题:如何使用Python以跨平台方式检查路径是绝对路径还是相对路径?

UNIX绝对路径以“ /”开头,而Windows则以字母“ C:”或“ \”开头。python是否具有标准功能来检查路径是绝对路径还是相对路径?

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


回答 0

os.path.isabsTrue如果路径是绝对的,False则返回,否则返回。该文档说它可以在Windows中运行(我可以确认它可以在Linux中正常运行)。

os.path.isabs(my_path)

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)

回答 1

如果您真正想要的是绝对路径,则不必费心检查它是否是绝对路径,只需获取abspath

import os

print os.path.abspath('.')

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

回答 2

使用os.path.isabs


回答 3

import os.path

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

os.path.isabs('user')
False
import os.path

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

os.path.isabs('user')
False

回答 4

实际上,我认为以上答案均未解决真正的问题:跨平台路径。os.path的作用是加载OS依赖的’path’库版本。因此解决方案是显式加载相关的(OS)路径库:

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

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

回答 5

python 3.4 pathlib可用。

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

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

回答 6

换句话说,如果您不在当前工作目录中,那有点脏,但是对我有用。

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

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

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)