Merge text files

GroupDocs.Merger for Python via .NET makes it easy to combine multiple plain-text files into a single TXT file programmatically. No third-party software or text editor is required.

A file with the .TXT extension represents a text document that contains plain text organized in lines. Paragraphs are recognized by carriage returns, and the content is human-readable as a sequence of characters. Standard text documents can be opened in any text editor or word processing application on any operating system.

Steps to merge TXT files

  1. Create an instance of the Merger class and pass the path to the first (base) TXT file.
  2. Call merger.join() with the path to each additional TXT file to append.
  3. Call merger.save() with the desired output path to write the merged file.
from groupdocs.merger import Merger

def merge_text_documents():
    # Load the first text file as the merge base
    with Merger("./input.txt") as merger:
        # Append the second text file
        merger.join("./input2.txt")
        # Save the combined text file
        merger.save("./output.txt")

if __name__ == "__main__":
    merge_text_documents()

input.txt is a sample file used in this example. Click here to download it.

input2.txt is a sample file used in this example. Click here to download it.

EXAMPLE 1 EXAMPLE 1 EXAMPLE 1
EXAMPLE 2 EXAMPLE 2 EXAMPLE 2
EXAMPLE 3 EXAMPLE 3 EXAMPLE 3
EXAMPLE 4 EXAMPLE 4 EXAMPLE 4
EXAMPLE 5 EXAMPLE 5 EXAMPLE 5
EXAMPLE 6 EXAMPLE 6 EXAMPLE 6
EXAMPLE 1 EXAMPLE 1 EXAMPLE 1
EXAMPLE 2 EXAMPLE 2 EXAMPLE 2
EXAMPLE 3 EXAMPLE 3 EXAMPLE 3
EXAMPLE 4 EXAMPLE 4 EXAMPLE 4
[TRUNCATED]

Download full output

Explanation

  • Load base document: Merger("./input.txt") opens the first text file as the merge base inside a context manager.
  • Append second document: merger.join("./input2.txt") appends the content of the second file. Call join again for each additional file.
  • Save result: merger.save("./output.txt") writes the merged text to disk.

Merge TXT Live Demo

GroupDocs.Merger for Python via .NET provides an online TXT Merger App, which allows you to try it for free and check its quality and accuracy.

API reference

  • Merger — main class; join, save methods.

See also