目录中的Python最新文件

2024-05-03 04:56:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个脚本,其中我试图列出以.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'

Tags: pathkeyinpyos错误linexls
2条回答
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")]

您可以使用glob获取xls文件的列表。

import os
import glob

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

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

相关问题 更多 >