TypeError:期望一个字符缓冲区对象 - 同时尝试将整数保存为文本文件 [英] TypeError: expected a character buffer object - while trying to save integer to textfile

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

问题描述

我正在尝试制作一个简单的计数器,它应该跟踪我的程序执行了多少次。



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



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

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

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


但是我所得到的只是 TypeError:预期一个字符缓冲对象



编辑:



尝试解析 y 作为字符串:

  f.write(str(y))

给出

  IOError:[Errno 0]错误
write()的文本字符串?它说:


write(str) - > None。请注意,由于缓冲,请注意,在
之前可能需要使用flush()或close(),因为磁盘上的文件反映了写入的数据


所以你需要将 y 转换为 str 首先。



另请注意,字符串将被写入文件末尾的当前位置,已经读过旧的值了。使用 f.seek(0)获取文件的开头。



编辑:至于 IOError 此问题似乎相关。从那里引用:


对于允许读取和写入(或附加)的模式
(包括+号),流应该被刷新(fflush)
或重新定位(fseek,fsetpos,rewind),读取
操作之后是写入操作或写入操作
通过阅读操作。


所以,我建议你尝试 f.seek(0)也许问题消失了。


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

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

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()

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.

Edit:

Trying to parse y as a string:

f.write(str(y))

gives

IOError: [Errno 0] Error

解决方案

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

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.

So you need to convert y to str first.

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.`

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

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.

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

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

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