我需要使用python获取文件夹的最新文件。在使用代码时:

max(files, key = os.path.getctime)

我得到以下错误:

FileNotFoundError: [WinError 2] The system cannot find The file specified: 'a'


当前回答

我一直在Python 3中使用这个,包括文件名上的模式匹配。

from pathlib import Path

def latest_file(path: Path, pattern: str = "*"):
    files = path.glob(pattern)
    return max(files, key=lambda x: x.stat().st_ctime)

其他回答

在windows上有一个更快的方法(0.05s),调用一个bat脚本来做这个:

get_latest.bat

@echo off
for /f %%i in ('dir \\directory\in\question /b/a-d/od/t:c') do set LAST=%%i
%LAST%

其中\\ question中的\\directory\是您想要调查的目录。

get_latest.py

from subprocess import Popen, PIPE
p = Popen("get_latest.bat", shell=True, stdout=PIPE,)
stdout, stderr = p.communicate()
print(stdout, stderr)

如果它找到一个文件,stdout是路径,stderr是None。

使用stdout.decode("utf-8").rstrip()来获得文件名的可用字符串表示。

我一直在Python 3中使用这个,包括文件名上的模式匹配。

from pathlib import Path

def latest_file(path: Path, pattern: str = "*"):
    files = path.glob(pattern)
    return max(files, key=lambda x: x.stat().st_ctime)

(经过编辑以改进答案)

首先定义一个函数get_latest_file

def get_latest_file(path, *paths):
    fullpath = os.path.join(path, paths)
    ...
get_latest_file('example', 'files','randomtext011.*.txt')

你也可以使用文档字符串!

def get_latest_file(path, *paths):
    """Returns the name of the latest (most recent) file 
    of the joined path(s)"""
    fullpath = os.path.join(path, *paths)

如果你使用Python 3,你可以使用iglob代替。

返回最新文件名称的完整代码:

def get_latest_file(path, *paths):
    """Returns the name of the latest (most recent) file 
    of the joined path(s)"""
    fullpath = os.path.join(path, *paths)
    files = glob.glob(fullpath)  # You may use iglob in Python3
    if not files:                # I prefer using the negation
        return None                      # because it behaves like a shortcut
    latest_file = max(files, key=os.path.getctime)
    _, filename = os.path.split(latest_file)
    return filename

我缺乏评论的声誉,但ctime从Marlon Abeykoons的回应没有给我正确的结果。使用时光网就可以了。(关键= os.path.getmtime))

import glob
import os

list_of_files = glob.glob('/path/to/folder/*') # * means all if need specific format then *.csv
latest_file = max(list_of_files, key=os.path.getmtime)
print(latest_file)

对于这个问题,我找到了两个答案:

Python os.path.getctime Max不返回latest unix系统中python - getmtime()和getctime()的区别

赋给files变量的值是不正确的。使用下面的代码。

import glob
import os

list_of_files = glob.glob('/path/to/folder/*') # * means all if need specific format then *.csv
latest_file = max(list_of_files, key=os.path.getctime)
print(latest_file)