TypeError:应为字符缓冲区对象-尝试将整数保存到textfi时

2024-05-20 00:05:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图制作一个非常简单的计数器,用来记录我的程序执行了多少次。

首先,我有一个只包含一个字符的文本文件:0

然后打开文件,将其解析为int,将1添加到该值,然后尝试将其返回到文本文件:

f = open('testfile.txt', 'r+')
x = f.read()
y = int(x) + 1
print(y)
f.write(y)
f.close()

我想让y覆盖文本文件中的值,然后关闭它。

但我得到的只是TypeError: expected a character buffer object

编辑:

试图将y解析为字符串:

f.write(str(y))

给予

IOError: [Errno 0] Error

Tags: 文件txtcloseread记录计数器open字符
3条回答

请尝试下面的代码:

如我所见,您已经插入了“r+”或此命令,请以读取模式打开文件,这样您就无法对其进行写入,因此如果要覆盖,必须以写入模式“w”打开文件 文件内容和写入新数据,否则可以使用“a”将数据追加到文件中

我希望这会有帮助;)

f = open('testfile.txt', 'w')# just put 'w' if you want to write to the file 

x = f.readlines() #this command will read file lines

y = int(x)+1

print y
z = str(y) #making data as string to avoid buffer error
f.write(z)

f.close()
from __future__ import with_statement
with open('file.txt','r+') as f:
    counter = str(int(f.read().strip())+1)
    f.seek(0)
    f.write(counter)

你检查过write()的文档字符串吗?上面写着:

write(str) -> None. Write string str to file.

Note that due to buffering, flush() or close() may be needed before the file on disk reflects the data written.

所以你需要先把y转换成str

还要注意,字符串将被写入文件末尾的当前位置,因为您已经读取了旧值。使用f.seek(0)到达文件的开头

编辑:对于IOErrorthis issue似乎是相关的。一个引用:

For the modes where both read and writing (or appending) are allowed (those which include a "+" sign), the stream should be flushed (fflush) or repositioned (fseek, fsetpos, rewind) between either a reading operation followed by a writing operation or a writing operation followed by a reading operation.

所以,我建议你试试f.seek(0),也许问题就解决了。

相关问题 更多 >