如何获取文件夹中的最新文件?
- 2025-02-28 08:23:00
- admin 原创
- 62
问题描述:
我需要使用python获取文件夹的最新文件。使用代码时:
max(files, key = os.path.getctime)
我收到以下错误:
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'a'
解决方案 1:
分配给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:
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)
解决方案 3:
我缺乏评论的声誉,但 Marlon Abeykoons 的 ctime 回复并没有给我正确的结果。不过使用 mtime 就可以了。(key=os.path.get m time))
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 不返回最新的
python - unix 系统中 getmtime() 和 getctime() 之间的区别
解决方案 4:
我一直在 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)
解决方案 5:
我建议使用glob.iglob()
而不是glob.glob()
,因为它更有效率。
glob.iglob() 返回一个迭代器,它产生与 glob() 相同的值,但实际上并不同时存储它们。
这意味着glob.iglob()
将会更加高效。
我主要使用以下代码来查找与我的模式匹配的最新文件:
LatestFile = max(glob.iglob(fileNamePattern),key=os.path.getctime)
注意:函数有多种变体max
,如果要找到最新文件,我们将使用以下变体:max(iterable, *[, key, default])
它需要可迭代,因此您的第一个参数应该是可迭代的。如果要查找 nums 的最大值,我们可以使用以下变体:max (num1, num2, num3, *args[, key])
解决方案 6:
尝试按创建时间对项目进行排序。下面的示例对文件夹中的文件进行排序并获取最新的第一个元素。
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]
解决方案 7:
大多数答案都是正确的,但如果有获取最新的两个或三个最新信息的要求,那么它可能会失败或需要修改代码。
我发现下面的示例更有用且更相关,因为我们可以使用相同的代码来获取最新的 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
解决方案 8:
在 Windows 上,有一种更快的方法(0.05 秒),调用执行此操作的 bat 脚本:
获取最新信息
@echo off
for /f %%i in ('dir \\directoryinquestion /b/a-d/od/t:c') do set LAST=%%i
%LAST%
\directoryinquestion
您要调查的目录在哪里。
获取最新信息
from subprocess import Popen, PIPE
p = Popen("get_latest.bat", shell=True, stdout=PIPE,)
stdout, stderr = p.communicate()
print(stdout, stderr)
如果找到文件stdout
路径则为stderr
无。
用于stdout.decode("utf-8").rstrip()
获取文件名的可用字符串表示形式。
解决方案 9:
(编辑以改进答案)
首先定义一个函数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
解决方案 10:
我尝试使用上述建议,但我的程序崩溃了,然后我发现我试图识别的文件已被使用,当尝试使用“os.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,'*'))))
此代码获取两组文件列表之间的不常见对象,它不是最优雅的,如果同时创建多个文件,它可能会不稳定
解决方案 11:
在 Linux 上,您还可以shell
从python
subprocess.run
需要python 3.5+
import subprocess
def find_latest_files(target_dir, count):
cmd = f"ls -t {target_dir} | head -n{count}"
try:
output = subprocess.run(cmd, shell=True, text=True, capture_output=True, check=False)
except subprocess.CalledProcessError as err:
sys.exit(f"Error: finding last modified file {err.output[1]}")
# returns a list[]
return output.stdout.splitlines()
扫码咨询,免费领取项目管理大礼包!