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:
- 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.
- 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.
Example 2: Adding new content to the file while keeping the old content with ‘a+’ as an access mode.
A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes etc.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course