Python - How To Concatenate Multiple Files Into a Single File in Python

ID : 398

viewed : 74

Tags : PythonPython File

vote vote

95

Python is a robust and general-purpose programming language heavily used in many domains these days.

Python’s simple syntax and a torrent of services working behind the scenes make tasks such as object-oriented programming, automated memory management, and file handling seamless.

We can easily create files, read files, append data, or overwrite data in existing files using Python. It can handle almost all the available file types with the help of some third-party and open-source libraries.

This article teaches how to concatenate multiple files into a single file using Python.

Concatenate Multiple Files Into a Single File in Python

To concatenate multiple files into a single file, we have to iterate over all the required files, collect their data, and then add it to a new file. Refer to the following Python code that performs a similar approach.

filenames = ["1.txt", "2.txt", "3.txt", "4.txt", "5.txt"]  with open("new-file.txt", "w") as new_file:     for name in filenames:         with open(name) as f:             for line in f:                 new_file.write(line)                          new_file.write("\n") 

The Python code above contains a list of filenames or file paths to the required text files. Next, it opens or creates a new file by new-file.txt.

Then it iterates over the list of filenames or file paths. Each file creates a file descriptor, reads its content line by line, and writes it to the new-file.txt file.

At the end of each line, it appends a newline character or \n to the new file.

  • Related HOW TO?