假设文件名格式为"文件名_日期.txt",日期格式为"%Y-%m-%d",可以使用以下代码实现:

import os
from datetime import datetime

folder_path = 'path/to/folder' # 文件夹路径
latest_file = None
latest_date = datetime.min

for filename in os.listdir(folder_path):
    if '_' not in filename: # 跳过不符合格式的文件名
        continue
    file_date_str = filename.split('_')[-1].replace('.txt', '') # 提取日期字符串
    try:
        file_date = datetime.strptime(file_date_str, '%Y-%m-%d') # 转换为日期对象
    except ValueError:
        continue # 跳过日期格式不符的文件名
    if file_date > latest_date: # 更新最新日期的文件
        latest_file = filename
        latest_date = file_date

if latest_file is not None:
    latest_file_path = os.path.join(folder_path, latest_file)
    print(latest_file_path)
else:
    print("No file found.")

该代码遍历文件夹中的所有文件名,提取文件名中的日期字符串,转换为日期对象,并与最新日期进行比较,选出包含最新日期的文件名。如果找到了最新日期的文件,则打印该文件的完整路径;否则打印"No file found."

用python遍历文件夹中文件名包含日期的文件并选出包含最新日期的文件

原文地址: https://www.cveoy.top/t/topic/fctb 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录