如何使用Python以跨平台方式检查路径是绝对路径还是相对路径?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3320406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if a path is absolute path or relative path in cross platform way with Python?
提问by prosseek
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?
UNIX 绝对路径以“/”开头,而 Windows 以字母“C:”或“\”开头。python 是否有标准函数来检查路径是绝对路径还是相对路径?
采纳答案by Donald Miner
os.path.isabsreturns Trueif the path is absolute, Falseif not. The documentationsays it works in windows (I can confirm it works in Linux personally).
os.path.isabsTrue如果路径是绝对路径,False则返回,否则返回。文档说它适用于 Windows(我可以确认它适用于 Linux)。
os.path.isabs(my_path)
回答by kennytm
Use os.path.isabs.
回答by Alex Bliskovsky
import os.path
os.path.isabs('/home/user')
True
os.path.isabs('user')
False
回答by Wayne Werner
And if what you really wantis the absolute path, don't bother checking to see if it is, just get the abspath:
如果您真正想要的是绝对路径,请不要费心检查它是否是,只需获取abspath:
import os
print os.path.abspath('.')
回答by Shoham
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:
实际上,我认为上述答案都没有解决真正的问题:跨平台路径。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
回答by Mahendra
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)
回答by Praveen
From python 3.4pathlibis available.
从python 3.4pathlib是可用的。
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:/')

