文件操作系列之os模块(二)

240 阅读1分钟

1. 相关属性

这里以D:\workspace\Python_excerise目录和D:\workspace\Python_excerise\README.md文件为例

image-20220508163829123.png

image-20220508164400761.png

1.1 获取最后一次的访问时间

os.path.getatime(path):获取path路径最后一次的访问时间,返回值是一个时间戳。如果path路径不存在或无法访问,则引发OSError
print(os.path.getatime(r'D:\workspace\Python_excerise'))

result:

1652007330.3330455

1.2 获取最后一次的修改时间

os.path.getmtime(path):获取path路径最后一次的修改时间,返回值是一个时间戳。如果path路径不存在或无法访问,则引发OSError
print(os.path.getmtime(r'D:\workspace\Python_excerise'))

result:

1652007329.958891

1.3 获取创建时间

os.path.getctime(path):获取path路径的创建时间,返回值是一个时间戳。如果path路径不存在或无法访问,则引发OSError
print(os.path.getctime(r'D:\workspace\Python_excerise'))

result:

1651853904.9950013

1.4 获取大小

os.path.getsize(path):获取path路径的大小,以字节为单位,返回值是一个时间戳。如果path路径不存在或无法访问,则引发OSError
print(os.path.getsize(r'D:\workspace\Python_excerise'))

result:

4096

1.5 查询当前工作路径

os.getcwd():查询当前工作路径
print(os.getcwd())

result:

D:\workspace\Python_excerise

2.操作系统相关

2.1 查询操作系统名称

os.name:查询当前操作系统的名称。如果是Windows系统,返回nt;如果是Linux/UNIX系统,返回posix。

2.2 查询路径分隔符

os.sep:查询当前操作系统的路径分隔符。如果是Windows系统,返回\;如果是Linux/UNIX系统,返回/;如果是苹果Mac OS系统,返回:。

2.3 查询行终止符

os.linesep:查询当前操作系统的行终止符。如果是Windows系统,返回\r\n;如果是Linux/UNIX系统,返回\n;如果是苹果Mac OS系统,返回\r。

2.4 获取当前目录

os.curdir:获取当前目录
print(os.curdir)

result:

.

2.5 获取当前父目录

os.pardir:获取当前父目录
print(os.pardir)

result:

..