Python Practice › File Handling Programs › Program 3
Append to a file
Write a Python program to append data to an existing file.
Output
line 1 line 2 line 3
Approach
- Mode “a” writes at the end and keeps the existing content.
Solution
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
Learn the concept
New to this topic? Read the lesson, then come back.