在Python中,可以使用os
模块和sorted
函数来按添加日期排序获取目录中的文件列表。
下面是一个示例代码:
import os
# 指定目录路径
directory = '/path/to/directory'
# 获取目录中的所有文件
files = [os.path.join(directory, file) for file in os.listdir(directory) if os.path.isfile(os.path.join(directory, file))]
# 按添加日期排序
sorted_files = sorted(files, key=lambda x: os.path.getmtime(x))
# 输出排序后的文件列表
for file in sorted_files:
print(file)
解释:
os.listdir()
函数获取目录中的所有文件的文件名。os.path.isfile()
函数判断路径是否为文件,以过滤掉目录和其他非文件。os.path.getmtime()
函数获取文件的最后修改时间作为排序的依据。sorted()
函数,传入key
参数为os.path.getmtime
的匿名函数,对文件列表进行排序。这样,就可以按添加日期排序获取目录中的文件列表。
上一篇:按天加权计算每月的周数据之和
下一篇:按添加时间排序列表