在 Python 3.6.2 上写入文件然后读取它

2023-11-29

target=open("test.txt",'w+')
target.write('ffff')
print(target.read())

运行以下 python 脚本时(test.txt 是一个空文件),它会打印一个空字符串。

但是,当重新打开文件时,它可以很好地读取它:

target=open("test.txt",'w+')
target.write('ffff')
target=open("test.txt",'r')
print(target.read())

这将根据需要打印出“ffff”。

为什么会发生这种情况?即使我在第 2 行更新了“目标”,并且我必须将 test.txt 重新分配给它,“目标”是否仍然被认为没有内容?


文件具有读/写位置。写入文件会将该位置放在写入文本的末尾;读取从同一位置开始。

将该位置放回到开头seek method:

with open("test.txt",'w+') as target:
    target.write('ffff')
    target.seek(0)  # to the start again
    print(target.read())

Demo:

>>> with open("test.txt",'w+') as target:
...     target.write('ffff')
...     target.seek(0)  # to the start again
...     print(target.read())
...
4
0
ffff

这些数字是返回值target.write() and target.seek();它们是写入的字符数和新位置。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Python 3.6.2 上写入文件然后读取它 的相关文章

随机推荐