Python Practice › File Handling Programs › Program 2
Overwrite a file
Write a Python program to overwrite the content of an existing file.
Output
new content
Approach
- Opening in mode “w” empties the file before writing.
Solution
with open("data.txt", "w") as f: f.write("old content\n") with open("data.txt", "w") as f: f.write("new content\n") print(open("data.txt").read())Output
new content
Line by line
Lines 4-5
The second “w” open erased “old content” before writing.
Learn the concept
New to this topic? Read the lesson, then come back.