Python os.path.isabs()
Python中的os.path.isabs()方法用于检查指定的路径是否为绝对路径。
在Unix平台上,绝对路径以正斜杠(‘ / ‘)开始,而在Windows上,删除任何可能的驱动器号后,绝对路径以反斜杠(‘ \ ‘)开始。
语法:os.path.isabs(path)
参数:
path:表示文件系统路径的类路径对象。
类路径对象是表示路径的字符串或字节对象。
返回类型:此方法返回一个类bool的布尔值。如果指定的路径是绝对路径,此方法返回True,否则返回False。
示例1
使用os.path.isabs()方法(在Unix平台上)
# Python program to explain os.path.isabs() method
# importing os.path module
import os.path
# Path
path = '/home/User/Documents'
# Check whether the
# specified path is an
# absolute path or not
isabs = os.path.isabs(path)
print(isabs)
# Path
path = 'home/User/Documents/'
# Check whether the
# specified path is an
# absolute path or not
isabs = os.path.isabs(path)
print(isabs)
# Path
path = '../User/Documents/'
# Check whether the
# specified path is an
# absolute path or not
isabs = os.path.isabs(path)
print(isabs)
输出:
True
False
False
示例2
使用os.path.isabs()方法(在Windows上)
# Python program to explain os.path.isabs() method
# importing os.path module
import os.path
# Path
path = r"C:\\Users\\Documents"
# Check whether the
# specified path is an
# absolute path or not
isabs = os.path.isabs(path)
print(isabs)
# Path
path = r"\\User\\Documents"
# Check whether the
# specified path is an
# absolute path or not
isabs = os.path.isabs(path)
print(isabs)
# Path
path = r"User\\Documents"
# Check whether the
# specified path is an
# absolute path or not
isabs = os.path.isabs(path)
print(isabs)
输出:
True
True
False