今天碰到了一個非常有意思的python特性。本來我是想打開一個文件,在文件的末尾接下去輸入一些內容的,代碼如下:
f = open('test.txt', 'r+') f.write(content) f.close()
結果發現無論我寫什么東西,content的內容總是會從文件開頭寫入,並且覆蓋掉原來的內容。查了官方文檔,也不知道應該怎么做。
但偶然間我發現了接到末尾寫入的方法,代碼如下:
f = open('test.txt', 'r+') f.read() f.write(content) f.close()
沒錯,只是添加了一行f.read(),之后你的write函數就會自動接到末尾進行寫入了。去翻了下官方文檔,貌似沒有提及這個。
read
(size)Read and return at most size characters from the stream as a single
str
. If size is negative orNone
, reads until EOF.
write
(s)Write the string s to the stream and return the number of characters written.