Python Program to Append the Content of One File to the End of Another File

This is a Python Program to append the contents of one file to another file.

Problem Description

The 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.

Problem Solution

1. Take the name of the file to be read from and the file to append into from the user.
2. Open the file to be read and read the content of the file and store it in a variable.
3. Open the file to append the data to and write the data stored in the variable into the file.
4. Close both the files.
5. Exit.

Program/Source Code

Here is source code of the Python Program to append the contents of one file to another file. The program output is also shown below.

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

1. User must enter the name of the file to be read from and the file to append into.
2. The file to be read is opened using open() function in the read mode.
3. The contents of the file read using read() function is stored in a variable and then the file is closed.
3. The file to append the data to is opened in the append mode and the data stored in the variable is written into the file.
4. The second file is then closed..

advertisement
advertisement
Runtime Test Cases
 
Case 1:
 
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!!
 
Case 2:
Enter file to be read from: out.txt
Enter file to be appended to: out1.txt
 
Contents of file test.txt: 
world
Contents of file test1.txt (before appending):
Hello
 
Contents of file test1.txt (after appending):
Hello world

Sanfoundry Global Education & Learning Series – Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.