python 按照修改时间进行文件读取

函数介绍:

  • 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

 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值