当 read() 将字节数作为参数时,Python 文件 write() 陷入追加模式

Spe*_*ero 5 python file

为什么这两个非常相似的代码表现如此不同?

代码1:

with open("new.txt", 'w+') as f:
    f.write("this is a line")

with open("new.txt", 'r+') as f:
    f.write("***")
    f.read()  # << note here
    f.seek(0)
    print(f.read())
Run Code Online (Sandbox Code Playgroud)

输出:***s is a line

代码2:

with open("new.txt", 'w+') as f:
    f.write("this is a line")

with open("new.txt", 'r+') as f:
    f.write("***")
    f.read(1)  # << note here
    f.seek(0)
    print(f.read())
Run Code Online (Sandbox Code Playgroud)

输出:this is a line***

Python版本:Python 3.10.6 (tags/v3.10.6:9c7b4bd, Aug 1 2022, 21:53:49) [MSC v.1932 64 bit (AMD64)] on win32