如何对比目录文件列表,为未匹配文件生成更新版?
问题
我有两个目录,分别存放旧数据与新数据。文件在目录间迁移时,文件名会从old-filename.ext更新为old-filename-updated.ext,且文件扩展名长度不固定。我希望实现以下功能:检查新目录中是否存在对应文件名的更新版文件,若不存在则创建新的更新版文件。
目前我编写了如下代码:
for files in old_dir: old_files = [:-5] #longest file extension is 4 chars long for file in new_dir: if old_files in new_dir: lst_updated_files.append(old.files)
这段代码能生成新目录中已匹配的文件名列表,但我在此处遇到瓶颈:如何处理剩余未匹配的旧文件,在更新目录中生成对应的新版本文件?
解决方案
步骤1:正确提取旧文件的基础名称(适配任意扩展名)
原代码里的old_files = [:-5]是语法错误,而且硬切片的方式无法适配任意长度的扩展名。可以用os.path.splitext拆分文件名和扩展名,精准提取不含扩展名的基础名称:
import os # 替换为你的实际目录路径 old_dir_path = "/your/old/directory/path" new_dir_path = "/your/new/directory/path" # 获取两个目录下的所有文件名 old_filenames = os.listdir(old_dir_path) new_filenames = os.listdir(new_dir_path) # 整理新目录中已存在的更新版文件对应的基础名集合 existing_updated_bases = set() for new_file in new_filenames: if "-updated" in new_file: # 拆分扩展名,去掉"-updated"得到原基础名 base_name, ext = os.path.splitext(new_file) original_base = base_name.replace("-updated", "") existing_updated_bases.add(original_base)
步骤2:处理未匹配的旧文件,生成更新版
遍历旧文件,判断其基础名是否不在已存在的更新版集合中,若不存在则创建对应的更新版文件(这里以复制原文件并重命名为例,也可按需改为创建空文件):
import shutil lst_updated_files = [] for old_file in old_filenames: old_file_full_path = os.path.join(old_dir_path, old_file) # 跳过目录,只处理文件 if not os.path.isfile(old_file_full_path): continue # 拆分旧文件的基础名和扩展名 old_base, old_ext = os.path.splitext(old_file) # 判断该基础名的更新版是否已存在 if old_base not in existing_updated_bases: # 构造更新后的文件名 new_file_name = f"{old_base}-updated{old_ext}" new_file_full_path = os.path.join(new_dir_path, new_file_name) # 复制原文件到新目录并重命名(保留元数据) shutil.copy2(old_file_full_path, new_file_full_path) # 记录已创建的更新文件 lst_updated_files.append(new_file_name)
关键注意点
- 用
os.path.splitext拆分文件名,适配任意长度的扩展名,避免硬切片的局限性。 - 用集合存储已存在的更新版基础名,判断效率远高于遍历列表。
- 处理时跳过目录,避免误操作非文件类型的条目。
- 若不需要复制原文件内容,仅需创建空文件,可把
shutil.copy2替换为open(new_file_full_path, 'w').close()。
内容的提问来源于stack exchange,提问作者Ryan
相关产品推荐
相关产品推荐

