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

如何在Python中将多文件中的指定字符串添加至空列表并保存到文件

Python实现多文件指定字符串收集与保存

核心需求

从多个文件中查找指定字符串,将所有出现的该字符串存入列表,同时按编号+字符串的格式保存到新文件中。

完整实现代码

import os

def collect_and_save_string(target_dir, target_str, output_file):
    # 初始化存储字符串的列表
    found_strings = []
    # 用于编号的计数器
    count = 1

    # 遍历目标目录下的所有文件
    for filename in os.listdir(target_dir):
        file_path = os.path.join(target_dir, filename)
        # 跳过目录,只处理文件
        if not os.path.isfile(file_path):
            continue
        # 可根据需要过滤文件类型,比如只处理txt文件:if filename.endswith('.txt'):
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                # 逐行读取文件内容
                for line in f:
                    # 检查当前行是否包含目标字符串
                    if target_str in line:
                        # 统计一行内的出现次数,若一行有多个重复会全部计数
                        occurrences = line.count(target_str)
                        for _ in range(occurrences):
                            found_strings.append(target_str)
                            # 写入结果文件,带编号
                            with open(output_file, 'a', encoding='utf-8') as out_f:
                                out_f.write(f"{count}.{target_str}\n")
                            count += 1
        except Exception as e:
            print(f"处理文件 {filename} 时出错: {e}")
    
    return found_strings

# 示例调用
if __name__ == "__main__":
    # 配置参数,替换为你的实际需求
    target_directory = "./your_target_files"  # 目标文件所在目录
    target_string = "Hello_World"             # 要查找的指定字符串
    output_filename = "Searched_Strings.txt"  # 结果保存文件名

    result_list = collect_and_save_string(target_directory, target_string, output_filename)
    print(f"共找到 {len(result_list)} 次目标字符串,已保存到 {output_filename}")
    # 如需查看收集到的列表,可取消下面注释
    # print(result_list)

代码说明

  • 文件遍历:通过os.listdir遍历目标目录,用os.path.isfile跳过子目录;可添加filename.endswith('.txt')这类条件过滤特定格式文件。
  • 字符串查找:逐行读取文件内容,用line.count(target_str)统计每行内目标字符串的出现次数,避免遗漏同一行的重复匹配。
  • 数据存储:每找到一次目标字符串,就添加到found_strings列表,同时以编号.字符串的格式追加写入结果文件,保证顺序和编号正确。
  • 异常处理:捕获文件读写时的异常,防止单个文件出错导致整个程序中断。

示例效果

若目标字符串"Hello_World"在多个文件中共出现10次,Searched_Strings.txt的内容为:

1.Hello_World
2.Hello_World
3.Hello_World
4.Hello_World
5.Hello_World
6.Hello_World
7.Hello_World
8.Hello_World
9.Hello_World
10.Hello_World

同时result_list列表中将包含10个"Hello_World"元素。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 11:42:59