【问题标题】:Get the latest file in every directory using python使用python获取每个目录中的最新文件
【发布时间】:2017-12-02 09:41:34
【问题描述】:

我想在当前工作目录的每个目录中找到最新的 zip 文件。我有这段代码可以在一个文件夹中找到最新的文件:

import glob
import os

list_of_files = glob.glob('/path/to/folder/*.zip') 
latest_file = max(list_of_files, key=os.path.getctime)
print latest_file

如何在所有文件夹中找到最新的文件?

【问题讨论】:

  • 你说的“所有文件夹”是什么意思?像所有人一样?
  • 例如,如果我有一个包含 5 个文件夹的当前工作目录并且每个文件夹都有自己的文件。
  • os.listdir 会列出所有文件和文件夹,可以递归调用

标签: python python-2.7 file


【解决方案1】:

Python 3.5+

import glob

list_of_files = glob.glob('/path/to/folder/**/*.zip', recursive=True)
latest_file = max(list_of_files, key=os.path.getctime)
print(latest_file)

引用glob.glob的文档:

如果递归为真,模式** 将匹配任何文件以及零个或多个目录和子目录。如果模式后跟 os.sep,则只有目录和子目录匹配。


对于旧版本:

Python 2.2+:

import fnmatch
import os

list_of_files = []
for root, dirnames, filenames in os.walk('/path/to/folder'):
    for filename in fnmatch.filter(filenames, '*.zip'):
        matches.append(os.path.join(root, filename))
latest_file = max(list_of_files, key=os.path.getctime)
print latest_file

【讨论】:

  • 我试图运行 python 2.2+ 示例,但它给出了一个错误,说 max () arg 是一个空序列。
  • 你试过调试它吗?您确定上述目录中有一些 zip 文件吗?
猜你喜欢
  • 1970-01-01
  • 2021-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-28
  • 2011-08-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多