类型错误:应为字符缓冲区对象 - 尝试将整数保存到文本文件时 [英] TypeError: expected a character buffer object - while trying to save integer to textfile

查看:22
本文介绍了类型错误:应为字符缓冲区对象 - 尝试将整数保存到文本文件时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to make a very simple 'counter' that is supposed to keep track of how many times my program has been executed.

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

First, I have a textfile that only includes one character: 0

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

Then I open the file, parse it as an int, add 1 to the value, and then try to return it to the textfile:

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.

I'd like to have y overwrite the value in the textfile, and then close it.

But all I get is TypeError: expected a character buffer object.

尝试将 y 解析为字符串:

Trying to parse y as a string:

f.write(str(y))

给予

IOError: [Errno 0] Error

推荐答案

你检查过 write() 的文档字符串了吗?它说:

Have you checked the docstring of write()? It says:

write(str) -> 无.将字符串 str 写入文件.

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

注意,由于缓冲的原因,可能需要先flush()或close()磁盘上的文件反映了写入的数据.

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

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

So you need to convert y to str first.

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

Also note that the string will be written at the current position which will be at the end of the file, because you'll already have read the old value. Use f.seek(0) to get to the beginning of the file.`

至于 IOError这个问题 似乎相关.从那里引用:

As for the IOError, this issue seems related. A cite from there:

对于允许读写(或追加)的模式(包含+"号的那些),流应该被刷新(fflush)或重新定位(fseek、fsetpos、rewind)操作后跟写操作或写操作接着是读取操作.

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),也许问题就会消失.

So, I suggest you try f.seek(0) and maybe the problem goes away.

这篇关于类型错误:应为字符缓冲区对象 - 尝试将整数保存到文本文件时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆