Sometimes, we want to modify a text file with Python.
In this article, we’ll look at how to modify a text file with Python.
How to modify a text file with Python?
To modify a text file with Python, we can call the write
method.
For instance, we write
with open("foo.txt", "a") as f:
f.write("new line\n")
to open the foo.txt file with open
.
Then we call f.write
to append "new line\n"
into the file.
We can prepend text by call seek
with 0 to rewind to the beginning of the file.
For instance, we write
with open("foo.txt", "r+") as f:
old = f.read()
f.seek(0)
f.write("new line\n" + old)
to call f.read
to read the contents of the file into a string.
Then we call seek
with 0 to rewind to the beginning of the file.
Then we call f.write
to overwrite the file with "new line\n" + old
.
Conclusion
To modify a text file with Python, we can call the write
method.