TypeError: expected a character buffer object - while trying to save integer to textfile
Solution 1:
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.
Solution 2:
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)
Solution 3:
Just try the code below:
As I see you have inserted 'r+' or this command open the file in read mode so you are not able to write into it, so you have to open file in write mode 'w' if you want to overwrite the file contents and write new data, otherwise you can append data to file by using 'a'
I hope this will help ;)
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()