簡體   English   中英

目錄中的 Python 最新文件

[英]Python newest file in a directory

我正在編寫一個腳本,試圖列出以 .xls 結尾的最新文件。 這應該很容易,但我收到了一些錯誤。

代碼:

for file in os.listdir('E:\\Downloads'):
    if file.endswith(".xls"):
        print "",file
        newest = max(file , key = os.path.getctime)
        print "Recently modified Docs",newest

錯誤:

Traceback (most recent call last):
  File "C:\Python27\sele.py", line 49, in <module>
    newest = max(file , key = os.path.getctime)
  File "C:\Python27\lib\genericpath.py", line 72, in getctime
    return os.stat(filename).st_ctime
WindowsError: [Error 2] The system cannot find the file specified: 'u'
newest = max(file , key = os.path.getctime)

這將迭代文件名中的字符而不是文件列表。

你正在做類似max("usdfdsf.xls", key = os.path.getctime)而不是max(["usdfdsf.xls", ...], key = os.path.getctime)

你可能想要這樣的東西

files = [x for x in os.listdir('E:\\Downloads') if x.endswith(".xls")]
newest = max(files , key = os.path.getctime)
print "Recently modified Docs",newest

您可能還希望改進腳本,以便在您不在Downloads目錄中時它可以工作:

files = [os.path.join('E:\\Downloads', x) for x in os.listdir('E:\\Downloads') if x.endswith(".xls")]

您可以使用glob來獲取xls文件列表。

import os
import glob

files = glob.glob('E:\\Downloads\\*.xls')

print "Recently modified Docs",max(files , key = os.path.getctime)

如果您更喜歡最新的 pathlib 解決方案,這里是:

from pathlib import Path

XLSX_DIR = Path('../../somedir/')
XLSX_PATTERN = r'someprefix*.xlsx'

latest_file = max(XLSX_DIR.glob(XLSX_PATTERN), key=lambda f: f.stat().st_ctime)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM