我想打开一个文件,加载内容,然后将新内容写入该文件以覆盖文件中的所有内容。我进行了测试,但没有按预期工作:
handler = open('test.txt', 'w+')
for line in handler:
print(line)
它什么也没打印出来。看起来"w+"首先会擦除输出的所有内容,但根据文档:
Write and Read (‘w+’) : Open the file for reading and writing. For an existing file, data is truncated and over-written. The handle is positioned at the beginning of the file.
怎么了?
它在文档中明确表示:
对于现有文件,数据被截断并重写
这意味着数据将在打开文件时被删除
这里的读取选项表示
w+打开进行读取和写入,截断文件,但也允许您读回写入文件的内容