by BehindJava

Write a program to Append the Contents of One File to Another File in Python

Home » python » Write a program to Append the Contents of One File to Another File in Python

In this tutorial we are going to learn about appending the Contents of One File to Another File in Python.

Python Program to Append the Contents of One File to Another File

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()

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.
  4. 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.
  5. The second file is then closed..