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
.
Trying to parse y
as a string:
f.write(str(y))
gives
IOError: [Errno 0] Error
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)
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()
Source: Stackoverflow.com