python 通过文件的mtime时间比该文件小的最近的要给文件
要找到一个文件的mtime时间比该文件小的最近的另一个文件,可以使用os.listdir()函数列出目录中的所有文件,然后使用os.path.getmtime()函数获取文件的mtime时间。接下来,可以使用循环遍历所有文件,找到mtime时间比目标文件小且最接近的文件。
下面是一个示例代码:
import os
def find_closest_file(target_file):
target_mtime = os.path.getmtime(target_file)
closest_file = None
closest_mtime_diff = float('inf')
for file in os.listdir('.'):
if os.path.isfile(file):
mtime = os.path.getmtime(file)
if mtime < target_mtime and target_mtime - mtime < closest_mtime_diff:
closest_file = file
closest_mtime_diff = target_mtime - mtime
return closest_file
# 示例用法
target_file = 'example.txt'
closest_file = find_closest_file(target_file)
print(f"The closest file to '{target_file}' with a smaller mtime is '{closest_file}'.")
在上面的示例中,find_closest_file()函数接受一个目标文件名作为参数,并返回mtime时间比目标文件小且最接近的文件名。然后,我们可以使用target_file变量传递目标文件的名称,并打印出最接近的文件名。
请注意,上述示例假设目标文件和要比较的文件都在同一个目录下。如果目标文件和要比较的文件在不同的目录下,需要相应地修改代码。
原文地址: http://www.cveoy.top/t/topic/i7kP 著作权归作者所有。请勿转载和采集!