Overwrite a file

EasyFile Handling Programs · 2 of 38

Write a Python program to overwrite the content of an existing file.

Advertisement
Output
new content

Approach

  1. Opening in mode “w” empties the file before writing.

Solution

Python
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.

More file handling programs

← All 38 File Handling Programs

Leave a Comment