![](/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.