A very interesting Python feature was encountered today. Originally I want to open a file, at the end of the file to enter some content, the code is as follows:
f = open ('test.txt'r+') f.write (content) F.close ()
It turns out that no matter what I write, content is always written from the beginning of the file and overwrites the original content. I checked the official documents and didn't know what to do.
But by chance I found the method that was written at the end of the code as follows:
f = open ('test.txt'r+') f.read () f.write (content ) F.close ()
Yes, just add a line of F.read () and your write function will automatically be written to the end. Went over the official document, seemingly without mentioning it.
-
read
(
size)
-
Read and return at the very size characters from the stream as a single str
. If size is negative or None
, reads until EOF.
-
-
write
(
s)
-
Write The string s to the stream and return the number of characters written.
File input and output features under Python3 and how to overwrite file contents and next input