Open In App

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

Last Updated : 02 Feb, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • Append Only (‘a’): Open the file for writing. The file is made if it doesn’t exist. The handle is positioned at the top of the file. The data being written are going to be inserted at the top, after the prevailing data.
  • Append with Read (‘a+’): Open the file for reading and writing. The file is made if it doesn’t exist. The handle is positioned at the top of the file. The data being written are going to be inserted at the top, after the prevailing data.

Approach:

  • We will first open the file in the append mode i.e. make use of either ‘a’ or ‘a+’ access mode to open a file.
  • Now, we will simply add the content at the bottom of the file thus keeping the old content of the file.
  • Then, we will close the opened file in the program.

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.

Python3




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

Python3




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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads