target=open("test.txt",'w+')
target.write('ffff')
print(target.read())
Run Code Online (Sandbox Code Playgroud)
运行以下python脚本(test.txt是一个空文件)时,它会打印一个空字符串.
但是,重新打开文件时,它可以正常读取它:
target=open("test.txt",'w+')
target.write('ffff')
target=open("test.txt",'r')
print(target.read())
Run Code Online (Sandbox Code Playgroud)
这会根据需要打印出'ffff'.
为什么会这样?"目标"仍然被认为没有内容,即使我在第2行更新了它,我还要将test.txt重新分配给它吗?
文件具有读/写位置.写入文件会将该位置放在书面文本的末尾; 阅读从同一个位置开始.
使用该seek方法将该位置放回到开头:
with open("test.txt",'w+') as target:
target.write('ffff')
target.seek(0) # to the start again
print(target.read())
Run Code Online (Sandbox Code Playgroud)
演示:
>>> with open("test.txt",'w+') as target:
... target.write('ffff')
... target.seek(0) # to the start again
... print(target.read())
...
4
0
ffff
Run Code Online (Sandbox Code Playgroud)
这些数字的返回值target.write()和target.seek(); 它们是写入的字符数和新位置.