【问题标题】:Python newest file in a directory目录中的 Python 最新文件
【发布时间】:2016-04-05 16:57:57
【问题描述】:

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

【问题讨论】:

    标签: python file directory listdir


    【解决方案1】:
    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")]
    

    【讨论】:

    • Still go me 错误:Traceback (most recent call last): File "C:\Python27\sele.py", line 47, in &lt;module&gt; newest = max(files , 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: 'usage01.12.2015_31.12.2015(1).xls'
    • 更新了答案。这是因为你没有从 Downloads 目录运行它,所以getcttime 只在当前目录中查找,找不到文件。
    • 那行得通。现在我收到E:\Downloads\usage01.12.2015_31.12.2015(3).xls。如何只获取没有路径的文件名?
    • 在您的最终输出中使用 os.path.basename docs.python.org/2/library/os.path.html#os.path.basename
    【解决方案2】:

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

    import os
    import glob
    
    files = glob.glob('E:\\Downloads\\*.xls')
    
    print("Recently modified Docs", max(files , key=os.path.getctime))
    

    【讨论】:

      【解决方案3】:

      如果您更喜欢最新的 pathlib 解决方案,这里是:

      from pathlib import Path
      
      XLSX_DIR = Path('../../somedir/')
      XLSX_PATTERN = r'someprefix*.xlsx'
      
      latest_file = max(XLSX_DIR.glob(XLSX_PATTERN), key=lambda f: f.stat().st_ctime)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-12-08
        • 2017-12-02
        • 1970-01-01
        • 2021-11-22
        • 1970-01-01
        • 2012-03-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多