[英]python: How to get latest file in a directory with certain pattern
我想要具有特定模式的目录中的最新文件。 我可以找到最新的文件,但不知道如何包含模式。 请尝试提出仅涉及 os 库的解决方案。
def newest(DIR_PATH):
files = os.listdir(DIR_PATH)
FILE_LIST = [os.path.join(DIR_PATH, BASENAME) for BASENAME in files]
return max(FILE_LIST, key=os.path.getctime)
该目录有多种文件。 例如考虑以下两种文件。
xyz-2019-11-17_01-25-14.json
xyz-2019-11-17_01-25-14-trimmed.json
我想获取不以'-trimmed.json'结尾的最新文件。请建议。
你可能会使用
import os
from pathlib import Path as makePath
def find_youngest(path, pattern, n=1):
"""
find the file that matches a pattern and has the highest modification
timestamp if there are multiple files that match the pattern.
input:
path, string or pathlib.Path, where to look for the file(s)
pattern, string, pattern to look for in filename
n, integer, how many to return. defaults to 1
returns
filename(s) of youngest file(s), including path.
None if no file
"""
assert n >= 1, "n must be greater equal 1."
path = makePath(path)
files = [makePath(f) for f in path.glob(pattern) if os.path.isfile(f)]
sortfiles = sorted(files, key=lambda x: os.path.getmtime(x), reverse=True)
if sortfiles:
return sortfiles[:n]
return None
注意:如果您使用pathlib.Path.glob
,您还可以使用regex
模式进行字符串匹配。
基于特定文件名结尾出现的 select 文件的简单方法可能是
files = ['xyz-2019-11-17_01-25-14.json',
'xyz-2019-11-17_01-25-14-trimmed.json']
select = [f for f in files if not f.endswith('-trimmed.json')]
# select
# Out[35]: ['xyz-2019-11-17_01-25-14.json']
您可以像这样简单地 go :
def newest(DIR_PATH):
files = os.listdir(DIR_PATH)
FILE_LIST = [os.path.join(DIR_PATH, BASENAME) for BASENAME in files if not BASENAME.endswith("trimmed.json")]
return max(FILE_LIST, key=os.path.getctime)
有一个名为 glob 的库。 一探究竟。 https://docs.python.org/3/library/glob.html
此解决方案与“Florian H”在此处给出的解决方案几乎相同,但有一个细微差别,如果模式位于 endwith 不相关的文件名之间的某个位置。
def newest(DIR_PATH):
files = os.listdir(DIR_PATH)
FILE_LIST = [os.path.join(DIR_PATH, BASENAME) for BASENAME in files if "trimmed" not in BASENAME]
return max(FILE_LIST, key=os.path.getctime)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.