我需要使用python获取文件夹的最新文件。在使用代码时:
max(files, key = os.path.getctime)
我得到以下错误:
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'a'
发布于 2016-09-05 09:04:50
分配给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)
发布于 2016-09-05 09:09:56
max(files, key = os.path.getctime)
是相当不完整的代码。什么是files
?它可能是来自os.listdir()
的文件名列表。
但是这个列表只列出了文件名部分(又称“基名”),因为它们的路径是通用的。为了正确使用它,你必须将它与通向它的路径结合起来(并用来获得它)。
例如(未测试):
def newest(path):
files = os.listdir(path)
paths = [os.path.join(path, basename) for basename in files]
return max(paths, key=os.path.getctime)
发布于 2016-09-05 09:00:53
尝试按创建时间对项目进行排序。下面的示例对文件夹中的文件进行排序,并获取最新的第一个元素。
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]
https://stackoverflow.com/questions/39327032
复制相似问题