栏目分类:
子分类:
返回
终身学习网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
终身学习网 > IT > 软件开发 > 后端开发 > Python

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

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_foldercheckpoint_5000.txt

 

 

转载请注明:文章转载自 www.051e.com
本文地址:http://www.051e.com/it/1033817.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号