The Wayback Machine - https://web.archive.org/web/20241107013751/https://www.geeksforgeeks.org/how-to-keep-old-content-when-writing-to-files-in-python/
Open In App

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

Last Updated : 02 Feb, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.



Previous Article
Next Article

Similar Reads

How to Download Python Old Version and Install
Python is a popular programming language known for its simplicity and versatility. When we install Python in our systems we always install the latest version of it but there may be situations where we need to install an older version of Python due to compatibility reasons or to work on legacy projects so that we can use old features of Python that
2 min read
Comparing Old-Style and New-Style Classes in Python
In Python, the difference between old-style and new-style classes is based on the inheritance from the built-in object class. This distinction was introduced in Python 2.x and was fully adopted in Python 3.x, where all classes are new-style classes. In this article, we will see the difference between the old-style and new-style classes in Python. P
4 min read
Reading and Writing CSV Files in Python
CSV (Comma Separated Values) format is the most common import and export format for spreadsheets and databases. It is one of the most common methods for exchanging data between applications and popular data format used in Data Science. It is supported by a wide range of applications. A CSV file stores tabular data in which each data field is separa
4 min read
Writing files in background in Python
How to write files in the background in Python? The idea is to use multi-threading in Python. It allows us to write files in the background while working on another operation. In this article, we will make a 'Asyncwrite.py' named file to demonstrate it. This program adds two numbers while it will also write a file in the background. Please run this
2 min read
Writing CSV files in Python
CSV (Comma Separated Values) is a simple file format used to store tabular data, such as spreadsheets or databases. Each line of the file represents a data record, with fields separated by commas. This format is popular due to its simplicity and wide support. Ways to Write CSV Files in PythonBelow are the ways by which we can write CSV files in Pyt
11 min read
Reading and Writing XML Files in Python
Extensible Markup Language, commonly known as XML is a language designed specifically to be easy to interpret by both humans and computers altogether. The language defines a set of rules used to encode a document in a specific format. In this article, methods have been described to read and write XML files in python. Note: In general, the process o
8 min read
Reading and Writing to text files in Python
Python provides built-in functions for creating, writing, and reading files. Two types of files can be handled in Python, normal text files and binary files (written in binary language, 0s, and 1s). Text files: In this type of file, Each line of text is terminated with a special character called EOL (End of Line), which is the new line character ('
9 min read
How to merge multiple excel files into a single files with Python ?
Normally, we're working with Excel files, and we surely have come across a scenario where we need to merge multiple Excel files into one. The traditional method has always been using a VBA code inside excel which does the job but is a multi-step process and is not so easy to understand. Another method is manually copying long Excel files into one w
4 min read
How to keep your PC awake automatically using Python?
In this article, we are going to discuss how to keep your PC awake using Python. In order to perform this task, we are going to use an external Python module. Here we will be using a python package PyAutoGUI (cross-platform GUI automation Python module used to programmatically control the mouse & keyboard. ) This will keep your PC awake forever
2 min read
How to drop duplicates and keep one in PySpark dataframe
In this article, we will discuss how to handle duplicate values in a pyspark dataframe. A dataset may contain repeated rows or repeated data points that are not useful for our task. These repeated values in our dataframe are called duplicate values. To handle duplicate values, we may use a strategy in which we keep the first occurrence of the value
3 min read
Keep Decimal places in branca Colormap using Folium
Creating effective visualizations with geographic data often involves using colormaps to represent different data values on a map. Folium, a powerful Python library for visualizing geospatial data, leverages the capabilities of the branca module to generate colormaps. However, a common issue users encounter is the rounding of decimal places in the
3 min read
Python | Writing to an excel file using openpyxl module
Prerequisite : Reading an excel file using openpyxl Openpyxl is a Python library for reading and writing Excel (with extension xlsx/xlsm/xltx/xltm) files. The openpyxl module allows Python program to read and modify Excel files. For example, user might have to go through thousands of rows and pick out few handful information to make small changes b
3 min read
Writing to an excel sheet using Python
Using xlwt module, one can perform multiple operations on spreadsheet. For example, writing or modifying the data can be done in Python. Also, the user might have to go through various sheets and retrieve data based on some criteria or modify some rows and columns and do a lot of work. Let's see how to create and write to an excel-sheet using Pytho
2 min read
Reading and Writing JSON to a File in Python
The full form of JSON is Javascript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-
3 min read
Writing data from a Python List to CSV row-wise
Comma Separated Values (CSV) files a type of a plain text document in which tabular information is structured using a particular format. A CSV file is a bounded text format which uses a comma to separate values. The most common method to write data from a list to CSV file is the writerow() method of writer and DictWriter class. Example 1: Creating
2 min read
Writing Tests using Selenium Python
Selenium's Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. Through Selenium Python API you can access all functionalities of Selenium WebDriver in an intuitive way. This article illustrates about how to use Selenium Python
2 min read
Python Pillow - Writing Text on Image
In this article, we will see how to write text on images with the Python Pillow module. Installation This module is not preloaded with Python. So to install it execute the following command in the command-line: pip install pillow Stepwise implementation: Step 1: Import Pillow library To complete this task the functions required from the Pillow libr
6 min read
Writing Scrapy Python Output to JSON file
In this article, we are going to see how to write scrapy output into a JSON file in Python. Using scrapy command-line shell This is the easiest way to save data to JSON is by using the following command: scrapy crawl <spiderName> -O <fileName>.json This will generate a file with a provided file name containing all scraped data. Note tha
2 min read
Python - Writing to video with OpenCV
In this article, we will discuss how to write to a video using OpenCV in Python. ApproachImport the required libraries into the working space.Read the video on which you have to write. Syntax: cap = cv2.VideoCapture("path")Create a output file using cv2.VideoWriter_fourcc() method Syntax: output = cv2.VideoWriter("path",cv2.VideoWriter_fourcc(*'MPE
1 min read
Writing Memory Efficient Programs Using Generators in Python
When writing code in Python, wise use of memory is important, especially when dealing with large amounts of data. One way to do this is to use Python generators. Generators are like special functions that help save memory by processing data one at a time, rather than all at once. The logic behind memory-efficient functions and Python generators is
5 min read
Writing a Domain Specific Language (DSL) in Python
The Domain Specific Languages (DSLs) are specialized programming languages tailored to specific problem domains or application areas. They enable developers to express domain-specific concepts and operations in concise intuitive syntax enhancing productivity and readability. In this article, we'll explore the process of designing and implementing a
3 min read
Reading and Writing lists to a file in Python
Reading and writing files is an important functionality in every programming language. Almost every application involves writing and reading operations to and from a file. To enable the reading and writing of files programming languages provide File I/O libraries with inbuilt methods that allow the creation, updation as well and reading of data fro
5 min read
Reading and Writing YAML File in Python
YAML (YAML Ain't Markup Language) is a human-readable data serialization standard that is commonly used for configuration files and data exchange between languages with different data structures. YAML is preferred in many cases due to its simplicity and readability compared to other formats like JSON or XML. In Python, working with YAML files is st
3 min read
Writing to file in Python
Python provides built-in functions for creating, writing, and reading files. There are two types of files that can be handled in Python, normal text files and binary files (written in binary language, 0s and 1s). Text files: In this type of file, Each line of text is terminated with a special character called EOL (End of Line), which is the new lin
7 min read
Tips for Writing Efficient and Maintainable Code with FastAPI
In this article, we will be discussing various strategies and techniques to help you write efficient and maintainable code with FastAPI, a modern and high-performance web framework for building APIs with Python. FastAPI is built on top of the popular library pydantic and provides numerous features to assist you in writing clean, efficient, and well
11 min read
Upload and Download files from Google Drive storage using Python
In this article, we are going to see how can we download files from our Google Drive to our PC and upload files from our PC to Google Drive using its API in Python. It is a REST API that allows you to leverage Google Drive storage from within your app or program. So, let's go ahead and write a Python script to do that. Requirements: Python (2.6 or
6 min read
Python | Write multiple files data to master file
Given a number of input files in a source directory, write a Python program to read data from all the files and write it to a single master file. Source directory contains n number of files, and structure is same for all files. The objective of this code is to read all the files one by one and then append the output into a single master file having
2 min read
How to create a list of files, folders, and subfolders in Excel using Python ?
In this article, we will learn How to create a list of Files, Folders, and Sub Folders and then export them to Excel using Python. We will create a list of names and paths using a few folder traversing methods explained below and store them in an Excel sheet by either using openpyxl or pandas module. Input: The following image represents the struct
12 min read
Upload files in Python
In this article, we will be looking into the process of file uploading in Python using cgi environment. One often comes across various web applications in which the client or the users is required to upload data in the form of a file(eg. image file, an audio file, text file, etc). There are two aspects to uploading a file, as there are two sides to
3 min read
Python | Reading .ini Configuration Files
This article aims to read configuration files written in the common .ini configuration file format. The configparser module can be used to read configuration files. Code #1 : Configuration File abc.ini ; Sample configuration file [installation] library = %(prefix)s/lib include = %(prefix)s/include bin = %(prefix)s/bin prefix = /usr/local # Setting
3 min read
three90RightbarBannerImg