Paths = [
'/one/two/three',
'/one/two/three/',
'/',
'.',
''
]
split() 将路径拆分为两部分,返回一个tuple(第二部分为最后一个元素,第一部分则是前面全部)
for path in Paths:
print(f'{path} : {os.path.split(path)}')
-------------------result-----------------------
/one/two/three : ('/one/two', 'three')
/one/two/three/ : ('/one/two/three', '')
/ : ('/', '')
. : ('', '.')
: ('', '')
basename() 返回的值等价于split()的第二部分
for path in Paths:
print(f'{path} : {os.path.basename(path)}')
-------------------result-----------------------
/one/two/three : three
/one/two/three/ :
/ :
. : .
:
dirname() 返回的值等价于split()的第一部分
splitext() 以.拆分文件名
path = 'filename.txt'
os.path.splitext(path)
('filename', '.txt')
commonprefix() 取一个路径列表作为参数,返回一个字符串,表示所有路径中都出现的公共前缀。
paths = [
'/one/two/three/',
'/one/two/three/1',
'/one/two/threeload'
]
print(os.path.commonprefix(paths))
/one/two/three
commonpath() 取一个路径列表作为参数,返回一个字符串,表示所有路径中都出现的公共前缀,考虑路径分隔符。
paths = [
'/one/two/three/',
'/one/two/three/1',
'/one/two/threeload'
]
print(os.path.commonpath(paths))
/one/two
join() 将多个组合路径组成部分组合为一个值
paths= ['one','two','three']
os.path.join(*paths)
'one//two//three'
expanduser() 把可变部分自动转换为用户主目录
for user in ['', 'shellman','noman']:
path = '~' + user
print(f'{path} : {os.path.expanduser(path)}')
~ : C:\Users\admin
~shellman : C:\Users\shellman
~noman : C:\Users\noman
expandvars() 会扩展路径中出现的所有shell环境变量
os.environ['MYVAR'] = 'ltj'
os.path.expandvars('/path/my/$MYVAR')
'/path/my/ltj'
normpath() 清除多余的分隔符或相对路径部分
path = 'one/./two/./three'
os.path.normpath(path)
'one\\two\\three'
abspath() 把相对路径转换为绝对路径
paths = [
'.',
'./one/two',
'../one/two'
]
for path in paths:
print(f'{path} -:- {os.path.abspath(path)}')
. -:- C:\Users\admin
./one/two -:- C:\Users\admin\one\two
../one/two -:- C:\Users\one\two
getatime() 获取访问时间
getmtime() 获取修改时间
getctime() 获取创建时间
getsize() 获取文件中的数据量