Let the given two files be file1.txt
and file2.txt
. Our task — combine both files into a third file, say file3.txt. Here are the steps to merge.
- Open file1.txt and file2.txt in read mode.
- Open file3.txt in write mode.
- Read data from file1 and append it to a line.
- Read data from file2 and concatenate data from this file with the previous line.
- Write data from a line to file3
- Close all files
Note. For the program below to run successfully, file1.txt and file2.txt must be in the same folder.
Suppose the text files file1.txt
and file2.txt
contain the following data.
file1.txt
file2.txt
Below is the implementation.
|
Output:
Usage for a loop
The above approach can be shortened with a for loop. Below are the steps to merge.
- Create a list containing the file names.
- Open file3 in write mode.
- Loop through the list and open each file in read mode.
- Reading data from files and simultaneously writing data to file3.
- Close all files
Below is the implementation.
|
Output: