Append content to a file in Python

Python | Append content to a file: In this tutorial, we will learn how to append content to a file using the write() method in Python. By Shivang Yadav Last updated : July 05, 2023

Program Statement

Python program to append contents to file using write() method.

Program Description

We will append the data to the file using write() method in python.

We will use the concepts of file handling in python to append the contents to the file using write() method.

  • The write() method is used to write some text to the file.
  • For appending the contents to the end, we will open the file using 'a' mode.

Appending content to a file in Python

The following are the steps to append content to a file,

  • Step 1: Open the file in append mode using 'a'.
  • Step 2: Get the input data from the user and store it.
  • Step 3: write the contents to the file using write() method.

Python program to append content to a file

F=open("data.dat","a")

while(True):
   id=input("Enter Id:")
   name=input("Enter Name:")
   salary=input("Enter Salary:")

   data="{0},{1},{2}\n".format(id,name,salary)
   F.write(data)

   ch=input("Continue y/n?")

   if(ch=="n"):break
F.close()

Output

Enter Id:10032
Enter Name:John Does
Enter Salary:45000
Continue y/n?y
Enter Id:10323
Enter Name:Ram
Enter Salary:50000
Continue y/n?n

File Contents (data.dat):
10032,John Doe,45000
10323,Ram,50000

Explanation

In the above code, we have opened the file for writing using 'a' mode. After this we have taken input from the user. And using the write() method, we have appended the data to the file.

Python file handling programs »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.