Merge Text Files with Python

You can use the following code to merge multiple txt files into one:

# 定义要合并的txt文件列表
txt_files = ['file1.txt', 'file2.txt', 'file3.txt']

# 打开要写入的合并文件
with open('merged_file.txt', 'w') as outfile:
    # 遍历每个txt文件
    for file in txt_files:
        # 打开每个txt文件
        with open(file, 'r') as infile:
            # 将文件内容写入合并文件
            outfile.write(infile.read())

Save the above code as a Python script file, place the txt files to be merged in the same directory, and then run the script to combine multiple txt files into one file named merged_file.txt.

bannerAds