【问题标题】:Is there a python function to read the files in folder by the order of modified time?是否有python函数可以按修改时间的顺序读取文件夹中的文件?
【发布时间】:2020-10-31 07:53:38
【问题描述】:

我有一个包含文件的文件夹,1.pkl、2.pkl、11.pkl、12.pkl 是按顺序创建的。

使用代码“os.listdir(path)”读取文件夹时,文件顺序为:

1.pkl

11.pkl

12.pkl

2.pkl

如何按照修改时间的顺序读取文件?

【问题讨论】:

    标签: python-3.x file time


    【解决方案1】:

    试试os.stat

    path = '.'
    
    import os
    
    files_with_times = [(f, os.stat(f).st_mtime) for f in os.listdir(path)]
    for f,t in sorted(files_with_times, key=lambda x: x[1]):
        print(f)
    

    【讨论】:

    • 你不需要像这样手动装饰和取消装饰; sortedkey 参数已经为你做了这个(每个值只计算一次,然后重用它);这就是 为什么 他们从 cmp 函数切换到 key 函数。一个简单的sorted(files, key=lambda file: os.stat(file).st_mtime) 将在没有 Python 级别的 decorate-undecorate 的情况下完成这项工作。 os.scandir 可以在某些系统上更有效地执行此操作(因为它免费获得 mtime 信息,无需单独的 stat 调用)。
    【解决方案2】:

    同时使用the os.scandirthe sorted function可以高效地达到效果:

    entries = sorted(os.scandir(path), key=lambda ent: ent.stat().st_mtime)
    

    如果您不需要它产生的the DirEntry objects 的其他功能,则将简单的list 理解更改为.name.path 属性将解决它,例如获取名称(没有完整路径):

    names = [ent.name for ent in entries]
    

    【讨论】:

      猜你喜欢
      • 2018-07-28
      • 1970-01-01
      • 1970-01-01
      • 2014-05-14
      • 1970-01-01
      • 1970-01-01
      • 2018-09-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多