Append to a file

EasyFile Handling Programs · 3 of 38

Write a Python program to append data to an existing file.

Advertisement
Output
line 1
line 2
line 3

Approach

  1. Mode “a” writes at the end and keeps the existing content.

Solution

Python
with open("log.txt", "w") as f:    f.write("line 1\n") with open("log.txt", "a") as f:    f.write("line 2\n")    f.write("line 3\n") print(open("log.txt").read())
Output
line 1
line 2
line 3
Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More file handling programs

← All 38 File Handling Programs