
本文介绍一种基于文件系统直接查找的高效方法,利用 python 的 `os.listdir()` 和路径拼接,避免嵌套循环遍历,将第二组文件中与第一组同名的文件内容追加到对应文件末尾。
在处理大量按命名规则组织的文本文件时(如 aaa.txt, ant.txt, cat.txt),若需将第二组文件中与第一组同名的文件内容追加到第一组对应文件末尾,最直观的双重循环方案(O(n×m) 时间复杂度)确实低效且不必要——因为文件系统本身已提供 O(1) 的路径查找能力。
✅ 正确思路是:只遍历第二组文件列表,对每个文件名,直接构造其在第一组目录中的完整路径并检查是否存在。这样时间复杂度降至 O(m),其中 m 是第二组文件数量,完全规避了对第一组的重复扫描。
以下是经过优化、健壮且可直接运行的 Python 实现:
import os
import sys
def append_matching_files(target_dir, source_dir):
"""
将 source_dir 中存在的、且 target_dir 中同名文件也存在的 .txt 文件内容,
追加到 target_dir 对应文件末尾。
:param target_dir: 第一组文件所在目录(接收追加内容)
:param source_dir: 第二组文件所在目录(提供追加内容)
"""
if not os.path.isdir(target_dir) or not os.path.isdir(source_dir):
raise ValueError("目标目录或源目录不存在,请检查路径。")
for filename in os.listdir(source_dir):
# 仅处理 .txt 文件(可按需调整)
if not filename.lower().endswith('.txt'):
continue
source_path = os.path.join(source_dir, filename)
if not os.path.isfile(source_path):
continue
target_path = os.path.join(target_dir, filename)
if os.path.isfile(target_path): # ✅ 关键:仅当目标文件存在时才追加
try:
with open(source_path, 'r', encoding='utf-8') as src_f, \
open(target_path, 'a', encoding='utf-8') as dst_f:
dst_f.write('\n') # 可选:添加换行分隔
dst_f.writelines(src_f)
print(f"✓ 已追加 {filename} 到 {target_path}")
except (IOError, UnicodeDecodeError) as e:
print(f"⚠ 跳过 {filename}:{e}")
else:
print(f"ℹ {filename} 在目标目录中不存在,已跳过。")
if __name__ == '__main__':
if len(sys.argv) != 3:
print("用法:python appendfiles.py <目标目录> <源目录>")
sys.exit(1)
append_matching_files(sys.argv[1], sys.argv[2])? 关键优势说明:
- 零嵌套循环:不遍历第一组目录,仅依赖操作系统级路径查找(os.path.isfile() 内部由文件系统高效支持);
- 内存友好:逐文件流式读写,不加载全文本到内存;
- 健壮性增强:增加 .txt 后缀过滤、编码声明(utf-8)、异常捕获和日志反馈;
- 语义清晰:严格遵循“仅追加到已存在目标文件”的业务逻辑(如题干所述:“There is a chance that a file in the second group does not exist in the first group”)。
? 扩展提示:
- 若需自动创建缺失的目标文件(即把 bat.txt 从第二组复制为新文件到第一组),只需将 if os.path.isfile(target_path): 改为 if True:,并在 else 分支中使用 shutil.copy2();
- 如需支持通配符或正则匹配(例如只处理 c*.txt),可用 pathlib.Path(source_dir).glob("c*.txt") 替代 os.listdir();
- 对超大规模场景(数万文件),可进一步结合 concurrent.futures.ThreadPoolExecutor 并行化 I/O 操作(注意磁盘瓶颈)。
该方案兼顾简洁性、可维护性与生产就绪性,是文件名驱动批量合并任务的标准实践。










