Python r+模式写入为何从文件末尾开始而非当前指针位置?
Python文件处理:写入操作为何追加到文件末尾而非指定位置?
问题背景
我正在学习Python文件处理,编写了一段代码但输出不符合预期。
代码实现
with open("file.txt", "r+") as f: content = f.read(5) print(content, f.tell()) f.write("(testing the pointer)") f.seek(0) print(f.read())
文件初始内容
Hello, I'm trying file handling in python.
预期与实际输出
- 预期:
f.read(5)读取前5个字符后,文件指针移到第5位,f.write()从该位置开始替换字符,原剩余字符会出现在写入文本之后。 - 实际输出:
Hello 5 Hello, I'm trying file handling in python.(testing the pointer)
疑问:为何写入的文本被追加到文件末尾,而非从第5个索引位置开始替换?
环境信息:
- Python版本:3.14
- 操作系统:Windows
原因分析
这是Windows系统下r+模式文件处理的特性:读写切换时,若未显式定位,写入操作会自动跳转到文件末尾。
具体细节:
f.read(5)执行后,文件指针确实停在第5个字符的位置(索引5)。- 但Windows的文件系统机制中,从读取状态切换到写入状态时,Python的文件对象会默认将指针移到文件末尾,导致写入内容被追加。
- 要在当前指针位置写入,需在
f.write()前显式调用f.seek(f.tell()),强制确认指针位置,这样写入就会从当前位置开始覆盖原有字符。
修正后的代码
with open("file.txt", "r+") as f: content = f.read(5) print(content, f.tell()) # 显式定位到当前指针位置 f.seek(f.tell()) f.write("(testing the pointer)") f.seek(0) print(f.read())
修正后输出
Hello 5 Hello(testing the pointer) trying file handling in python.
内容的提问来源于stack exchange,提问作者Aditya Kumhar
相关产品推荐
相关产品推荐

