os.path 模块主要用于获取文件的属性。
以下是 os.path 模块的几种常用方法:
方法 | 说明 |
---|---|
os.path.abspath(path) | 返回绝对路径 |
os.path.basename(path) | 返回文件名 |
os.path.dirname(path) | 返回文件路径 |
os.path.getatime(path) | 返回最近访问时间(浮点型秒数) |
os.path.getmtime(path) | 返回最近文件修改时间 |
os.path.getctime(path) | 返回文件 path 创建时间 |
os.path.getsize(path) | 返回文件大小,如果文件不存在就返回错误 |
os.path.isabs(path) | 判断是否为绝对路径 |
os.path.isfile(path) | 判断路径是否为文件 |
os.path.isdir(path) | 判断路径是否为目录 |
os.path.islink(path) | 判断路径是否为链接 |
os.path.ismount(path) | 判断路径是否为挂载点 |
os.path.normpath(path) | 规范path字符串形式 |
os.path.realpath(path) | 返回path的真实路径 |
os.path.split(path) | 把路径分割成 dirname 和 basename,返回一个元组 |
os.path.splitext(path) | 分割路径,返回路径名和文件扩展名的元组 |
root@localhost test]# ls demo/
2-client.py 2-server.py 3-client.py 3-server.py client.py server.py testcases.txt
[root@localhost test]#
[root@localhost test]# python
Python 2.7.5 (default, Apr 28 2020, 14:27:15)
[GCC 4.8.5 20150623 (Loongson 4.8.5-39)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>>
>>> import os
>>> a = "demo/server.py"
>>>
>>> os.path.abspath(a)
'/root/test/demo/server.py'
>>> os.path.basename(a)
'server.py'
>>> os.path.dirname(a)
'demo'
>>>
>>> os.path.getatime(a)
1604130811.55054
>>> os.path.getmtime(a)
1602898663.2221506
>>> os.path.getctime(a)
1602898663.2729304
>>> os.path.getsize(a)
659
>>> os.path.isabs(a)
False
>>> os.path.isfile(a)
True
>>> os.path.isdir(a)
False
>>> os.path.islink(a)
False
>>> os.path.ismount(a)
False
>>> os.path.normpath(a)
'demo/server.py'
>>> os.path.realpath(a)
'/root/test/demo/server.py'
>>> os.path.split(a)
('demo', 'server.py')
>>> os.path.splitext(a)
('demo/server', '.py')
>>>