In python3, the file input and output features, and how to overwrite the file content and the next input,
Today I met a very interesting python feature. Originally, I wanted to open a file and input some content at the end of the file. The Code is as follows:
f = open('test.txt', 'r+')f.write(content)f.close()
The result shows that no matter what I write, the content is always written from the beginning of the file and overwrites the original content. I checked the official documentation and did not know how to do it.
But by accident, I found the method of writing to the end. The Code is as follows:
f = open('test.txt', 'r+')f.read()f.write(content)f.close()
Yes, just adding a row of f. read (), your write function will automatically be written to the end. After reviewing the official documentation, it seems that this is not mentioned.
-
read
(
size)
-
Read and return at most 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.