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

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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.mshxw.com
本文地址:https://www.mshxw.com/it/1033817.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号