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

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

我得到以下错误:

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


当前回答

我缺乏评论的声誉,但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()的区别

其他回答

尝试按创建时间对项目进行排序。下面的例子对文件夹中的文件进行排序,并获取最新的第一个元素。

import glob
import os

files_path = os.path.join(folder, '*')
files = sorted(
    glob.iglob(files_path), key=os.path.getctime, reverse=True) 
print files[0]

大多数答案是正确的,但如果有一个要求,如获得最新的2或3个,那么它可能会失败或需要修改代码。

我发现下面的示例更有用和相关,因为我们可以使用相同的代码来获得最新的2,3和n个文件。

import glob
import os

folder_path = "/Users/sachin/Desktop/Files/"
files_path = os.path.join(folder_path, '*')
files = sorted(glob.iglob(files_path), key=os.path.getctime, reverse=True) 
print (files[0]) #latest file 
print (files[0],files[1]) #latest two files

我一直在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)
max(files, key = os.path.getctime)

是相当不完整的代码。什么是文件?它可能是一个文件名列表,来自os.listdir()。

但此列表仅列出文件名部分(a.k.a.)。“basenames”),因为它们的路径是通用的。为了正确地使用它,您必须将它与通往它的路径(以及用于获得它的路径)结合起来。

如(未经测试):

def newest(path):
    files = os.listdir(path)
    paths = [os.path.join(path, basename) for basename in files]
    return max(paths, key=os.path.getctime)

我缺乏评论的声誉,但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()的区别