Open In App

How to keep old content when Writing to Files in Python?

In this article, we are going to discuss various approaches to keep old content while writing files in Python.

We can keep old content while using write in python by opening the file in append mode. To open a file in append mode, we can use either ‘a‘ or ‘a+‘ as the access mode. The definition of these access modes are as follows:



Approach:

We are going to use the below text file to perform all the approaches:



Below is the complete implementation of the approach explained above:

Example1: Adding new content to the file while keeping the old content with ‘a’ as an access mode.




# Python program to keep the old content of the file
# when using write.
  
# Opening the file with append mode
file = open("gfg input file.txt", "a")
  
# Content to be added
content = "\n\n# This Content is added through the program #"
  
# Writing the file
file.write(content)
  
# Closing the opened file
file.close()

Output:

Example 2: Adding new content to the file while keeping the old content with ‘a+’ as an access mode.




# Python program to keep the old content of the file
# when using write.
  
# Opening the file with append mode
file = open("gfg input file.txt", "a+")
  
# reach at first
file.seek(0)
  
# Reading the file
content = file.read()
  
# view file content
print(content)
  
# Content to be added
content = "\n\n# This Content is added through the program #"
  
# Writing the file
file.write(content)
  
# Closing the opened file
file.close()

Output:

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes etc.


Article Tags :