Program to append the content of one file to another file using Python

Introduction

The task is to append the text of one file to another file.

Program to append the content of one file to another file using Python File 2Program to append the content of one file to another file using Python File 1

Program

# Open files in read mode and print its content before appending

ipFile1 = open("first.txt", "r") 

print("Content of first file: ", ipFile1.read()) 

ipFile2 = open("second.txt", "r") 

print("Content of second file: ", ipFile2.read())  

ipFile1.close() 

ipFile2.close() 




#Open first file in read mode and second file in append mode

ipFile1 = open("first.txt", "r") 

ipFile2 = open("second.txt", "a+") 

#Append text of first file to second file

ipFile2.write(ipFile1.read()) 


ipFile1.seek(0) 

ipFile2.seek(0) 

#Print both files after appending

print("Content of second file: ", ipFile2.read()) 

#Close the files

ipFile1.close() 

ipFile2.close()

Output

Output before Append

Content of second file after append:-

Content of second file after append

Explanation

Approach:

  • Open both the files in read mode and print the content of files.
  • Again open both the files, this time first file in read mode and second file in append mode. This is because we are appending the content of first file to that of second file.
  • Append the content using write statement and move the cursor position to beginning using seek() method.
  • Print the content of second file after appending.
  • Close the files.

Author

  • Barry Allen

    A Full Stack Developer with 10+ years of experience in different domain including SAP, Blockchain, AI and Web Development.

    View all posts

Comments

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.