How to Write to an Existing File in Python


In this example, we will learn how to write to an existing file and overwrite any existing content using the open() function in Python.

Source Code

f = open('myfile3.txt', 'w')
f.write("Overwrite everything.")
f.close()

# Open and read the file after the overwriting:
f = open('myfile3.txt', 'r')
text = f.read()
print(text) 

Output:

Overwrite everything.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Advertisement