目录中的 Python 最新文件

标签 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'

最佳答案

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/

相关文章:

c++ - C++中如何检查文件夹是否有写权限

python - 无聊的AWK高手能不能帮忙转换一下这个Python程序呢?

c#检查给定文件路径是否包含根目录

python - Keras 回调实例没有属性 'set_model'

java - :/->\的文件路径问题

c# - 用所有已注册的文件类型(不仅仅是扩展名)填充 ComboBox 的最有效方法是什么

python-3.x - 如何在Django中创建一个文件夹来存储用户输入

JavaScript 目录

python - Pandas 以绝对最大值重新采样

python - 在 python pandas 中用下一行的 Start_date 填充 End_date 列