Program to read the data of two of the files and add it to a new file

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
  1. Create two variables and assign their values equal to an empty string.
  2. Open the first file using open(‘readcontent1.txt’) as f.
  3. Read and store the data in the first file in the first variable using read().
  4. Open the second file using open(‘readcontent2.txt’) as f.
  5. Read and store the data in the second file in the first variable using read().
  6. Add the new line at the end of the data in the first variable.
  7. Now add the data in the second variable to the first variable.
  8. Open the third file using open (‘writecontent.txt’, ‘w’) as f.
  9. 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.

 

 

extract characters from a text file into a list.

count the total number of characters in a file.

Leave a Comment