Python 合并 txt 文本内容

流程概述

本文将教会你如何使用 Python 合并多个 txt 文本文件的内容。整个流程如下图所示:

flowchart TD
    A(开始) --> B(获取文件列表)
    B --> C(遍历文件列表)
    C --> D(读取文件内容)
    D --> E(合并文件内容)
    E --> F(写入新文件)
    F --> G(结束)

具体步骤及代码解释

1. 获取文件列表

首先,你需要获取要合并的 txt 文件路径列表。可以使用 glob 模块来获取指定目录下的所有 txt 文件。以下是代码示例:

import glob

file_list = glob.glob("path/to/txt/files/*.txt")
  • glob.glob("path/to/txt/files/*.txt") 会返回一个符合指定路径模式的文件列表。例如,path/to/txt/files/*.txt 表示获取 path/to/txt/files/ 目录下的所有以 .txt 结尾的文件。

2. 遍历文件列表

接下来,你需要遍历文件列表,并逐个读取文件的内容。可以使用 for 循环来遍历文件列表。以下是代码示例:

for file_path in file_list:
    # 在此处添加代码

3. 读取文件内容

在每次循环中,你需要读取当前文件的内容并进行合并。可以使用 with open(file_path, 'r') as file 来打开文件并读取内容。以下是代码示例:

for file_path in file_list:
    with open(file_path, 'r') as file:
        content = file.read()
  • with open(file_path, 'r') as file 会以只读模式打开文件,并将文件对象赋值给 file 变量。
  • file.read() 会将文件的全部内容读取并返回。

4. 合并文件内容

在每次循环中,你需要将当前文件的内容合并到一个新的字符串中。可以使用 += 运算符来累加内容。以下是代码示例:

merged_content = ""

for file_path in file_list:
    with open(file_path, 'r') as file:
        content = file.read()
        merged_content += content
  • merged_content += content 会将当前文件的内容添加到 merged_content 字符串末尾。

5. 写入新文件

最后,你需要将合并后的内容写入一个新的文件中。可以使用 with open("path/to/merged_file.txt", 'w') as file 来打开一个新文件并写入内容。以下是代码示例:

with open("path/to/merged_file.txt", 'w') as file:
    file.write(merged_content)
  • with open("path/to/merged_file.txt", 'w') as file 会以写入模式打开一个新文件,并将文件对象赋值给 file 变量。
  • file.write(merged_content) 会将合并后的内容写入文件。

6. 完整代码

下面是整个流程的完整代码:

import glob

file_list = glob.glob("path/to/txt/files/*.txt")
merged_content = ""

for file_path in file_list:
    with open(file_path, 'r') as file:
        content = file.read()
        merged_content += content

with open("path/to/merged_file.txt", 'w') as file:
    file.write(merged_content)

以上代码将会合并 path/to/txt/files/ 目录下所有以 .txt 结尾的文件,并将合并后的内容写入 path/to/merged_file.txt 文件中。

总结

通过本文的指导,你已经学会了如何使用 Python 合并多个 txt 文本文件的内容。不同步骤的代码和注释帮助你理解了每一步的具体操作。祝你在日后的开发工作中能够灵活运用这些技巧!