gpt4 book ai didi

python - 如何读取目录中的文件属性?

转载 作者:太空狗 更新时间:2023-10-29 18:13:38 24 4
gpt4 key购买 nike

例如:

import os
print(os.listdir("path/to/dir"))

将列出目录中的文件。

如何获取目录中所有文件的文件修改时间?

最佳答案

在查找目录中所有文件的文件属性时,如果您使用的是 Python 3.5 或更新版本,请使用 os.scandir() function获取目录列表结合了文件属性。这可能比使用 os.listdir() 然后单独检索文件属性更有效:

import os

with os.scandir() as dir_entries:
for entry in dir_entries:
info = entry.stat()
print(info.st_mtime)

DirEntry.stat() function ,在Windows上使用时,不用再做任何额外的系统调用,文件修改时间就已经有了。数据已缓存,因此额外的 entry.stat() 调用不会进行额外的系统调用。

您还可以使用 pathlib module面向对象实例实现相同:

from pathlib import Path

for path in Path('.').iterdir():
info = path.stat()
print(info.st_mtime)

在较早的 Python 版本中,您可以使用 os.stat调用获取修改时间等文件属性。

import os

for filename in os.listdir():
info = os.stat(filename)
print(info.st_mtime)

st_mtime 是 python 2.5 及更高版本上的浮点值,表示自纪元以来的秒数;使用 timedatetime用于显示目的或类似目的解释这些的模块。

请注意,该值的精度取决于您使用的操作系统:

The exact meaning and resolution of the st_atime, st_mtime, and st_ctime attributes depend on the operating system and the file system. For example, on Windows systems using the FAT or FAT32 file systems, st_mtime has 2-second resolution, and st_atime has only 1-day resolution. See your operating system documentation for details.

如果您所做的只是获取修改时间,那么 os.path.getmtime方法是一个方便的快捷方式;它在底层使用 os.stat 方法。

但是请注意,os.stat 调用相对昂贵(文件系统访问),因此如果您对大量文件执行此操作,并且每个文件需要多个数据点,您最好使用 os.stat 并重用返回的信息,而不是使用 os.path 方便的方法,其中 os.stat 将被多次调用每个文件的次数。

关于python - 如何读取目录中的文件属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10960477/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com