目录

时间:2015-12-31 20:11:09

标签: python file directory listdir

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

2 个答案:

答案 0 :(得分:8)

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 :(得分:1)

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

import os
import glob

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

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