How to merge multiple files into a new file using Python?


Python makes it simple to create new files, read existing files, append data, or replace data in existing files. With the aid of a few open-source and third-party libraries, it can manage practically all of the file types that are currently supported.

We must iterate through all the necessary files, collect their data, and then add it to a new file in order to concatenate several files into a single file. This article demonstrates how to use Python to concatenate multiple files into a single file.

Using Loops

A list of filenames or file paths to the necessary python files may be found in the Python code below. Next, advanced_file.py is either opened or created.

The list of filenames or file paths is then iterated over. Each file generates a file descriptor, reads its contents line by line, and then writes the information to the advanced_file.py file.

It adds a newline character, or \n, to the new file at the end of each line.

Example - 1

Following is an example to merge multiple files nto a single file using for loop −

nameOfFiles = ["moving files.py", "mysql_access.py", "stored procedure python-sql.py", "trial.py"] with open("advanced_file.py", "w") as new_created_file: for name in nameOfFiles: with open(name) as file: for line in file: new_created_file.write(line) new_created_file.write("\n")

Output

As an output, a new python file is created with the name “advanced_file” which has all the existing mentioned python files in it.

Example - 2

In the following code we opened the existing file in read mode and the new created file i.e. advanced_file in write mode. After that we read the that frm both the files and added it in a string and wrote the data from string to the new created file. Finally, closed the files −

info1 = info2 = "" # Reading information from the first file with open('mysql_access.py') as file: info1 = file.read() # Reading information from the second file with open('trial.py') as file: info2 = file.read() # Merge two files for adding the data of trial.py from next line info1 += "\n" info1 += info2 with open ('advanced_file.py', 'w') as file: file.write(info1)

Output

As an output a new python file is created with the name “advanced_file” which has both the existing mentioned python files in it.

Updated on: 18-Aug-2022

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements