Q:

Append content to a file in Python

belongs to collection: Python file handling programs

0

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.

Steps to append contents of 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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to illustrate the solution of the problem

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

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Read contents of the file using readline() method ... >>
<< Python program to write data to file...