Python file program to append data to an existing file

In this python file program, we will append data to an existing file. Let’s consider we have an appendcontent.txt file with the below content. We will add a new line with append mode with the help of below-given steps.

				
					# readcontent.txt
Line1 : This is India.
Line2 : This is America.
Line3 : This is Canada.
Line4 : This is Australia.
				
			
Steps to solve the program
  1. Open the file by using open(“file name”,”a”).
  2. Where file name is the name of the file and a is an appending mode.
  3. Using write() add the data into the file it will not get overwritten.
  4. Close the file.
				
					# Open file with append mode
f=open("appendcontent.txt","a")
# write new line to the file
f.write("New Line : This is china")
# Close the file
f.close()
				
			

Output: Now open the readontent.txt file, then we will see the newly added line will be available.

Line1 : This is India.
Line2 : This is America.
Line3 : This is Canada.
Line4 : This is Australia.
New Line : This is china

 

 

overwrite the existing file content.

get the file’s first three and last three lines.

Leave a Comment