In this python file program, we will read the data of two of the files and add it to a new file with the help of the below-given steps. Let’s consider we have readcontent.txt1 and readcontent.txt2 files with the below content.
#readcontent.txt1
Line1 : This is India.
Line2 : This is America.
Line3 : This is Canada.
Line4 : This is Australia.
#readcontent.txt2
Line5 : This is Africa.
Line6 : This is Korea.
Line7 : This is Germany.
Line8 : This is China.
Steps to solve the program
- Create two variables and assign their values equal to an empty string.
- Open the first file using open(‘readcontent1.txt’) as f.
- Read and store the data in the first file in the first variable using read().
- Open the second file using open(‘readcontent2.txt’) as f.
- Read and store the data in the second file in the first variable using read().
- Add the new line at the end of the data in the first variable.
- Now add the data in the second variable to the first variable.
- Open the third file using open (‘writecontent.txt’, ‘w’) as f.
- Add the merged data to it using write().
# Create two empty strings
data = data2 = ""
# Open first file
with open('readcontent1.txt') as f:
# Read the data
data = f.read()
# Open second file
with open('readcontent2.txt') as f:
# Read the data
data2 = f.read()
# Add a new line
data += "\n"
# Combine data
data += data2
# Open third file in write mode and write the new data to it
with open ('writecontent.txt', 'w') as f:
f.write(data)
Output : Open the writecontent.txt file to see the result
Line1 : This is India.
Line2 : This is America.
Line3 : This is Canada.
Line4 : This is Australia.
Line5 : This is Africa.
Line6 : This is Korea.
Line7 : This is Germany.
Line8 : This is China.