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是否有标准函数来检查路径是绝对路径还是相对路径?
7 个解决方案
#1
141
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返回True,否则返回False。文档说它适用于Windows(我可以确认它可以在Linux中运行)。
os.path.isabs(my_path)
#2
31
And if what you really want is the absolute path, don't bother checking to see if it is, just get the abspath
:
如果你真正想要的是绝对路径,不要费心检查它是否是,只需得到abspath:
import os
print os.path.abspath('.')
#4
6
import os.path
os.path.isabs('\home\user')
True
os.path.isabs('user')
False
#5
1
The os.path
module will have everything you need.
os.path模块将拥有您需要的一切。
#6
1
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
#7
0
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)
#1
141
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返回True,否则返回False。文档说它适用于Windows(我可以确认它可以在Linux中运行)。
os.path.isabs(my_path)
#2
31
And if what you really want is the absolute path, don't bother checking to see if it is, just get the abspath
:
如果你真正想要的是绝对路径,不要费心检查它是否是,只需得到abspath:
import os
print os.path.abspath('.')
#3
#4
6
import os.path
os.path.isabs('\home\user')
True
os.path.isabs('user')
False
#5
1
The os.path
module will have everything you need.
os.path模块将拥有您需要的一切。
#6
1
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
#7
0
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)