猿问

如何在不替换字符的情况下对文件使用 write() 方法?

我有一个 .txt 文件,其内容是:


This is an example file.

These are its contents.

This is line 3.

如果我打开文件,移到开头,然后像这样写一些文本......


f = open(r'C:\Users\piano\Documents\sample.txt', 'r+')

f.seek(0, 0)

f.write('Now I am adding text.\n')

我期待的是文件读取:


Now I am adding text.

This is an example file.

These are its contents.

This is line 3.

...但它改为:


Now I am adding text.

.

These are its contents.

This is line 3.

那么为什么有些文本被替换而不是我正在写的文本被简单地添加到开头?我怎样才能解决这个问题?


一只斗牛犬
浏览 201回答 2
2回答
随时随地看视频慕课网APP

相关分类

Python
我要回答