SoFunction
Updated on 2025-03-04

Python implementation combines the contents of multiple txt files into one

The following is a simple Python script that allows multiple                                                                                                                                                                   �.txtMerge the contents of the file into one file:

Script code

import os

def merge_txt_files(input_dir, output_file):
    """
     Merge all txt files in the specified directory into one file.

     :param input_dir: Input directory containing txt file
     :param output_file: Output file path
     """
    try:
        with open(output_file, 'w', encoding='utf-8') as outfile:
            for filename in (input_dir):
                if ('.txt'):
                    file_path = (input_dir, filename)
                    with open(file_path, 'r', encoding='utf-8') as infile:
                        (())
                        ('\n')  # Add line breaks to distinguish different files        print(f"alltxtThe file has been merged into {output_file}")
    except Exception as e:
        print(f"An error occurred: {e}")

#User Exampleinput_directory = "path/to/your/txt/files"  # Replace with the directory path where your txt file is locatedoutput_file_path = "path/to/your/"  # Replace with the merged output file path
merge_txt_files(input_directory, output_file_path)

How to use

1. Set the directory path and output file path:

Replace input_directory as the directory path where the .txt file is stored.

Replace output_file_path for the path to the merge file you want to generate.

2. Run the script:

Make sure that your Python environment is installed and configured.

Run the script to save the generated merge file in the specified path.

Things to note

Make sure that all .txt files are encoded consistently (for example, UTF-8) to avoid encoding problems.

If there are many files in the directory, the script will be read one by one, which may take some time.

Method supplement

python merge multiple txt files by line

import os
 
 
def read_txt(start, last):
    text_list = []
    for n in range(start, last):
        path = ('hypotheses', 'hyp' + str(n) + '.')
        with open(path, 'r') as f:
            dic = {i: sen for i, sen in enumerate(())}
            text_dic = {n: dic}
        text_list.append(text_dic)
    return text_list
 
 
sen_list = []
all_sen_list = read_txt(0, 100)
for j in range(0, 1000):
    for k in range(0, 100):
        srn = all_sen_list[k - 1][k][j]
        sen_list.append(srn)
        with open('', 'w', encoding='utf-8') as f:
            (sen_list

python merge multiple txt files

1. Read and write file content line by line

# Define the list of txt files to be mergedfile_list = ['', '', '']

# Create a new file to store the merged contentwith open('merged_file.txt', 'w') as merge_file:
    # Open each txt file in turn and read its contents    for file_name in file_list:
        with open(file_name, 'r') as file:
            # Read each line and write to a new file            for line in file:
                merge_file.write(line)

# Close all open filesmerge_file.close()

2. Use shutil module to copy file contents

import shutil

# Define the list of txt files to be mergedfile_list = ['', '', '']

# Create a new file to store the merged contentwith open('merged_file.txt', 'wb') as merge_file:
    # Open each txt file in turn and copy its contents into a new file    for file_name in file_list:
        with open(file_name, 'rb') as file:
            (file, merge_file)

# Close all open filesmerge_file.close()

This is the end of this article about python's implementation of merging the contents of multiple txt files into one. For more related python's merging contents of multiple txt files, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!