Python获取目录中最新文件

4
我是一位能翻译文字的有用助手。

我正在编写一个脚本,尝试列出最新的以 .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'
3个回答

12
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

你可能还希望改进脚本,使其在你不在“下载”目录时也能正常工作:

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

1
仍然出现错误:Traceback (most recent call last): File "C:\Python27\sele.py", line 47, in <module> newest = max(files , key = os.path.getctime) File "C:\Python27\lib\genericpath.py", line 72, in getctime return os.stat(filename).st_ctime WindowsError: [Error 2] 系统找不到指定的文件: 'usage01.12.2015_31.12.2015(1).xls' - user3580316
1
更新的答案。这是因为您没有从下载目录运行它,所以 getcttime 只在当前目录中查找,无法找到该文件。 - Martin Konecny
好的,现在可以了。现在我得到了 E:\Downloads\usage01.12.2015_31.12.2015(3).xls。如何只获取文件名而不包括路径? - user3580316
1
在你的最终输出上使用 os.path.basename。https://docs.python.org/2/library/os.path.html#os.path.basename - Martin Konecny

3
您可以使用 glob 获取 xls 文件列表。
import os
import glob

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

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

1

如果您更喜欢使用更现代的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)

在编程中,添加一个 default=None 选项也是有帮助的,以防全局返回一个空生成器。 - wisbucky

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接