我需要使用python获取文件夹的最新文件。在使用代码时:
max(files, key = os.path.getctime)
我得到以下错误:
FileNotFoundError: [WinError 2] The system cannot find The file specified: 'a'
我需要使用python获取文件夹的最新文件。在使用代码时:
max(files, key = os.path.getctime)
我得到以下错误:
FileNotFoundError: [WinError 2] The system cannot find The file specified: 'a'
当前回答
赋给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)
其他回答
大多数答案是正确的,但如果有一个要求,如获得最新的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
在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()来获得文件名的可用字符串表示。
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)
我建议使用glob.iglob()而不是glob.glob(),因为它更有效。
返回一个迭代器,该迭代器产生与glob()相同的值,但实际上不会同时存储它们。
这意味着glob.iglob()将更有效。
我主要使用下面的代码来查找与我的模式匹配的最新文件:
最后文件= max(filenameb),key=os.path.get时间)
注意: max函数有多种变体,为了找到最新的文件,我们将使用下面的变体: Max (iterable, *[, key, default])
它需要iterable所以你的第一个参数应该是iterable。 在寻找最大nums的情况下,我们可以使用下面的变体:max (num1, num2, num3, *args[, key])
赋给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)