我需要使用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'
当前回答
大多数答案是正确的,但如果有一个要求,如获得最新的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
其他回答
我尝试使用上面的建议,我的程序崩溃了,然后我发现我试图识别的文件被使用了,当我尝试使用'os.path. path. path. path时。Getctime '它崩溃了。 最后对我有用的是:
files_before = glob.glob(os.path.join(my_path,'*'))
**code where new file is created**
new_file = set(files_before).symmetric_difference(set(glob.glob(os.path.join(my_path,'*'))))
这段代码获得了两组文件列表之间的不常见对象 它不是最优雅的,如果同时创建多个文件,它可能不会稳定
大多数答案是正确的,但如果有一个要求,如获得最新的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
(经过编辑以改进答案)
首先定义一个函数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
赋给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)
我建议使用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])