How to keep old content when Writing to Files in Python?
Last Updated :
02 Feb, 2021
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
file = open ( "gfg input file.txt" , "a" )
content = "\n\n# This Content is added through the program #"
file .write(content)
file .close()
|
Output:
Example 2: Adding new content to the file while keeping the old content with ‘a+’ as an access mode.
Python3
file = open ( "gfg input file.txt" , "a+" )
file .seek( 0 )
content = file .read()
print (content)
content = "\n\n# This Content is added through the program #"
file .write(content)
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.
Please Login to comment...