Table of Contents
Introduction
The task is to merge the content of two files(say file1 and file2) into third file file3.
Program
Approach 1
readftxtFile = readstxtFile = "" with open('firstFile.txt') as readFile: readftxtFile = readFile.read() with open('secFile.txt') as readFile: readstxtFile = readFile.read() readftxtFile += "\n" readftxtFile += readstxtFile with open ('outputFile.txt', 'w') as readFile: readFile.write(readftxtFile) readFile.close()
Output:
Approach 2
readFiles = ['firstFile.txt', 'secFile.txt'] with open('outputFile.txt', 'w') as writeFile: for file in readFiles: with open(file) as inputFile: writeFile.write(inputFile.read()) writeFile.write("\n")
Output
Explanation
Approach 1:
- Open the two content files in read mode and third file in write mode.
- Read the lines of first file and store it in a variable temp.
- Read the lines of second file and concatenate it to temp.
- Write the data to third file.
- Close the files.
Approach 2:
- Assign the filename to a list variable.
- Open the third file in write mode.
- Iterate through the list variable and open the files in read mode to read the lines.
- Read the lines and append the lines to third file simultaneously.
- Close the files.
0 Comments