函数介绍:
- os.path.getmtime(path)
用于获取指定路径的最后修改时间。此方法返回一个浮点值,该值表示自纪元以来的秒数。如果文件不存在或无法访问,则此方法会引发OSError。
参考:Python os.path.getmtime()用法及代码示例 - 纯净天空 (vimsky.com)
- time.ctime([ sec ]) sec为要转化为字符串时间的秒数
用于把一个时间戳(按秒计算的浮点数)转化为 time.asctime() 的形式。如果参数未给或者为None的时候,默认使用 time.time() 为参数。
参考:Python time.ctime() 方法 - Python3 基础教程 - 简单教程,简单编程 (twle.cn)
代码:
import os
import time
test_path = 'cxy/codes/test_folder/checkpoint_1000.txt'
sec = os.path.getmtime(test_path)
t = time.ctime(sec)
print(sec, t)
实例:
如何按照文件修改的时间进行文件读取,比如读取最后修改的某种指定格式的文件。
import os
import time
output_directory = 'cxy/codes/test_folder'
file_list = os.listdir(output_directory)
print(file_list) # ['checkpoint_1000.txt', 'checkpoint_2000.txt', 'checkpoint_3000.txt', 'checkpoint_4000.txt', 'checkpoint_5000.txt']
file_list.sort(key=lambda fn: os.path.getmtime(os.path.join(output_directory, fn))
if fn.startswith("checkpoint_") else 0)
print(file_list) # ['checkpoint_1000.txt', 'checkpoint_2000.txt', 'checkpoint_3000.txt', 'checkpoint_4000.txt', 'checkpoint_5000.txt']
if file_list and file_list[-1].startswith("checkpoint_"):
print(os.path.join(output_directory, file_list[-1])) # cxy/codes/test_folder\checkpoint_5000.txt