我正在编写一个脚本,试图列出以 .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
您可能还想改进脚本,以便它在您不在下载目录中时也能正常工作:
files = [os.path.join('E:\\Downloads', x) for x in os.listdir('E:\\Downloads') if x.endswith(".xls")]
关于目录中的 Python 最新文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34551190/