how to read then overwrite a file with python

Do you want to know the details regarding “how to read then overwrite a file with python”. If yes, you’re in the correct article.

how to read then overwrite a file with python

 pythonCopywith open('myFolder/myfile.txt', "r") as myfile:
    data = myfilef.read()

with open('myFolder/myfile.txt', "w") as myfile:
    myfile.write(newData)
with open("foo.txt", "w") as foofile:
    foofile.write("This is the contents of foo")
 
# open it back up again and verify what's in there
with open("foo.txt") as foofile:
    print(foofile.read())
# -> This is the contents of foo
 
# now open it and again and write to it
with open("foo.txt", "w") as foofile:
    foofile.write("Foo has been overwritten!")
 
# open it yet again and see what it says
with open("foo.txt") as foofile:
    print(foofile.read())
# -> Foo has been overwritten!

Final Words

I hope this article helps you to know about “how to read then overwrite a file with python”. If you have any doubts regarding this tutorial please let us know via the comment section. Share this tutorial with your friends and family via social networks.

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coder Diksha. Here, I post about programming to help developers.

Share on:

Leave a Comment