gpt4 book ai didi

python - 将数据保存到文本文件时遇到问题

转载 作者:行者123 更新时间:2023-12-01 05:25:11 24 4
gpt4 key购买 nike

当我尝试将数据写入文件时,没有收到任何错误,但当我尝试读回文件时,文件中没有任何内容。我做错了什么?

test = open('/Users/MYUSER/Desktop/test.txt', 'r+')

test.write("RANDOME STRING\n")

test.read()

''

最佳答案

您需要使用 file.seek 将文件指针移动到文件的开头在调用 .read() 之前。当您向文件写入内容时,文件指针会移动到文件末尾,这就是为什么在文件对象上调用 .read() 返回一个空字符串。

演示:

>>> test = open('abc1', 'r+')
>>> test.write('foo')
>>> test.read()
''
>>> test.seek(0)
>>> test.read()
'foo'

关于python - 将数据保存到文本文件时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21516831/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com