2 python directory file 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
Run Code Online (Sandbox Code Playgroud)
错误:
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'
Run Code Online (Sandbox Code Playgroud)
newest = max(file , key = os.path.getctime)
Run Code Online (Sandbox Code Playgroud)
这将迭代文件名中的字符而不是文件列表.
你正在做的事情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
Run Code Online (Sandbox Code Playgroud)
您可能还希望改进脚本,以便在您不在Downloads目录中时它可以工作:
files = [os.path.join('E:\\Downloads', x) for x in os.listdir('E:\\Downloads') if x.endswith(".xls")]
Run Code Online (Sandbox Code Playgroud)