TypeError: expected a character buffer object - while trying to save integer to textfile


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

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.


Trying to parse y as a string:



IOError: [Errno 0] Error
8/1/2014 3:38:57 PM

Accepted Answer

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.

3/20/2012 12:50:51 PM

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow