![](/img/trans.png)
[英]Get the file name which contains the latest timestamp in a directory using python
[英]Get the latest file in every directory using python
我想在当前工作目录的每个目录中找到最新的 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
如何在所有文件夹中找到最新的文件?
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 为真,则模式
**
将匹配任何文件以及零个或多个目录和子目录。 如果模式后跟 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.