我想在当前工作目录的每个目录中找到最新的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
如何在所有文件夹中找到最新文件?
答案 0 :(得分:1)
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 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
的文档:
如果recursive为true,则模式
**
将匹配任何文件以及零个或多个目录和子目录。如果模式后跟os.sep,则只有目录和子目录匹配。