You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何读取含多文件路径的文本并按用户指定条件合并文件内容

文本文件内容合并脚本实现

需求描述

  • 读取output.txt中存储的所有文件路径
  • 接收用户输入的字符数阈值n
  • 将字符数不超过n的目标文件内容,合并到单个输出文件中

现有output.txt生成代码

import os
import sys

def output():
    extensions = ('.txt', '.csv')
    exclude = {'AppData', 'System32', 'Program Files', '.vscode', 'Videos', 'Games', 'Program Files (x86)'}
    
    # 遍历C盘并写入符合条件的文件路径
    with open("output.txt", "a") as f:
        sys.stdout = f
        for dname, dirs, files in os.walk('C:'):
            dirs[:] = [d for d in dirs if d not in exclude]
            for fname in files:
                if fname.lower().endswith(extensions):
                    fpath = os.path.join(dname, fname)
                    print(fpath)
    
    # 遍历D盘
    with open("output.txt", "a") as f:
        sys.stdout = f
        for dname, dirs, files in os.walk('D:'):
            dirs[:] = [d for d in dirs if d not in exclude]
            for fname in files:
                if fname.lower().endswith(extensions):
                    fpath = os.path.join(dname, fname)
                    print(fpath)
    
    # 遍历E盘
    with open("output.txt", "a") as f:
        sys.stdout = f
        for dname, dirs, files in os.walk('E:'):
            dirs[:] = [d for d in dirs if d not in exclude]
            for fname in files:
                if fname.lower().endswith(extensions):
                    fpath = os.path.join(dname, fname)
                    print(fpath)

output()

注:原代码存在重复逻辑,已做轻微优化,改用with语句自动管理文件句柄,避免手动关闭可能出现的遗漏

满足需求的合并脚本

def merge_files_by_char_limit():
    # 1. 读取output.txt中的文件路径
    file_paths = []
    try:
        with open("output.txt", "r", encoding="utf-8", errors="ignore") as f:
            for line in f:
                line = line.strip()
                # 过滤注释行、空行和自身路径
                if not line or line.startswith("#") or line == "output.txt":
                    continue
                file_paths.append(line)
    except FileNotFoundError:
        print("错误:未找到output.txt文件,请先运行生成脚本创建该文件")
        return

    # 2. 获取用户输入的字符数阈值n
    while True:
        n_input = input("请输入字符数阈值n:")
        if n_input.isdigit():
            n = int(n_input)
            break
        print("请输入有效的正整数")

    # 3. 合并符合条件的文件内容
    output_filename = "merged_output.txt"
    with open(output_filename, "w", encoding="utf-8") as output_file:
        for path in file_paths:
            try:
                with open(path, "r", encoding="utf-8", errors="ignore") as target_file:
                    content = target_file.read()
                    # 检查字符数是否符合要求
                    if len(content) <= n:
                        # 写入文件路径作为分隔标识,方便查看来源
                        output_file.write(f"--- 来自文件:{path} ---\n")
                        output_file.write(content)
                        output_file.write("\n\n")
            except Exception as e:
                print(f"无法读取文件{path}:{str(e)}")

    print(f"合并完成,结果已保存到{output_filename}")

if __name__ == "__main__":
    merge_files_by_char_limit()

脚本说明

  • 路径读取:自动过滤output.txt中的注释行、空行以及自身路径,避免无效处理
  • 输入校验:循环获取用户输入,确保阈值是有效的正整数
  • 异常处理:捕获文件不存在、无法读取等异常情况,避免脚本崩溃并给出提示
  • 合并标识:在合并内容中加入原文件路径的分隔线,方便区分不同文件的内容
  • 编码兼容:读取文件时使用errors="ignore"处理编码不兼容的情况,提升脚本鲁棒性

内容的提问来源于stack exchange,提问作者ThundeR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 23:00:56