本文介绍了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()的文本字符串?它说:

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



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



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

所以,我建议你尝试 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:

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:

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

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

11-02 18:03