如何用Python复制指定文件名前缀的最新创建日期文件
解决方案
你原来的代码逻辑错误在于:试图在循环里用max(file_name, key=os.path.getctime)完全无效——max需要接收一个文件路径的列表作为输入,而不是单个文件名,且在遍历每个文件时判断单个文件的"最大值"没有筛选意义。
正确的思路是先收集所有符合前缀的文件,再从中找出创建时间最新的那个,最后仅复制这一个文件:
import shutil import os source_folder = 'insert path' destination_folder = 'insert path' prefix = 'Sam_Thompson' # 收集所有符合前缀的文件完整路径 matching_files = [] for file_name in os.listdir(source_folder): file_path = os.path.join(source_folder, file_name) if os.path.isfile(file_path) and file_name.startswith(prefix): matching_files.append(file_path) if matching_files: # 找出创建时间最新的文件(Windows下getctime是创建时间,Unix下是更改时间;Unix如需创建时间用os.path.getbirthtime) latest_file = max(matching_files, key=lambda x: os.path.getctime(x)) # 生成目标路径 dest_path = os.path.join(destination_folder, os.path.basename(latest_file)) # 复制文件 shutil.copy(latest_file, dest_path) print('Copied latest file:', os.path.basename(latest_file)) else: print(f'No files found with prefix "{prefix}"')
关键细节说明:
- 用
os.path.join拼接路径,避免手动拼接时出现的跨系统路径分隔符问题(Windows用\,Unix用/)。 max函数通过lambda表达式指定按文件的创建时间(os.path.getctime)作为排序依据,直接从列表中提取最新文件路径。- 若运行环境是Unix/Linux/macOS,需要获取文件原始创建时间而非修改时间的话,将
os.path.getctime替换为os.path.getbirthtime即可。
内容的提问来源于stack exchange,提问作者Samantha Thompson
相关产品推荐
相关产品推荐

