Append data to file in Python

In append (a) mode , data will be added at the end of the file.
As the file pointer is positioned at the end of the file so existing data will not be overwritten.
fob=open('data1.txt','a')
fob.write("\nthis is  2nd line of text added")
You can open data1.txt and see the content inside.


To write and display
fob=open('data1.txt','a')
fob.write("\nthis is  2nd line of text added")
## Writting at the end  of file is over , now read
fob=open('data1.txt','r')
print(fob.read())
fob.close()
Output is here
this is first line of text
this is  2nd line of text added

Error Handling with Append

Use try-except to safely handle potential file errors:

try:
    fob = open('data1.txt', 'a')
    fob.write("\nNew line added.")
except IOError:
    print("Error opening file.")
finally:
    fob.close()

Appending Multiple Lines

Write multiple lines of text in append mode:

with open('data1.txt', 'a') as fob:
    fob.write("\nLine 1\nLine 2")

Use Case: Logging to a File

Appending logs for each program run:

with open('log.txt', 'a') as log_file:
    log_file.write("Program executed successfully.\n")

File Read File Write

Questions

  1. Enter name , mark in four subjects for students by creating a CSV file. A CSV file ( Comma separated value ) stores records in rows and each data is separated by comma. Here is a sample csv file data.
    1,Ravi,20,30,40,120
    2,Raju,30,40,50,130
    3,Alex,40,50,60,140
    4,Ronn,50,60,70,150

Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer