How to Append Contents of One File to Another in Python

How to Append Contents of One File to Another in Python

To append means to add on, usually to the end of something. You can also use append to mean to fix onto or to attach usually at the end. Sometimes you can change the meaning of a word by removing the suffix and appending another to it. This program takes the name of the file to be read from and the file to append into from the user and appends the contents of one file to another.and finally appends the content of one file to another file in this context.

STEP 1: Take the name of the file to be read from and the file to be appended into the user

STEP 2: Open the file to be read and read the content of the file and store it in a variable. The file to be read is opened using open() function in the read mode.

STEP 3: Open the file to append the data to and write the data stored in the variable into the file.  The file to append the data is opened in the append mode and the data stored in the variable is written into the file.

STEP 4:  Close both the files and exit from the program. 

name1 = input("Enter file to be read from: ")
name2 = input("Enter file to be appended to: ")
file = open(name1, "r")
data2 = file.read()
file.close()
fout = open(name2, "a")
fout.write(data2)
fout.close()

OUTPUT:

Enter file to be read from: test.txt
Enter file to be appended to: test1.txt
 
Contents of file test.txt: 
Appending!!
 
Contents of file test1.txt (before appending):
Original
 
Contents of file test1.txt (after appending):
Original Appending!!

Leave a Reply

Your email address will not be published. Required fields are marked *