1
1
1HAWK12021-12-24 17:33:27
Python
1HAWK1, 2021-12-24 17:33:27

Error reading file in python. How to fix?

f = open('counter.txt','r')
a = int(f.read())
a+=1
f.close()
print(a)
f = open('counter.txt','w')
f.write(a)
f.close()

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alan Gibizov, 2021-12-24
@phaggi

I suppose the point is that in the file - a line or lines. They contain, in addition to the numbers themselves, other characters - spaces, line breaks, carriage returns, end of file, etc.
Of course, you can make it work exactly the way you do it.
But apparently, you are reinventing the wheel on crutches.
After all, you need to store some data in the file - for example, the value of a parameter.
For this, they came up with formats - for example, JSON, XML, YAML, CSV, etc.
JSON is often used - there is a built-in library for it in Python, it is well described and more than flexible for any of your needs. Try to master.

A
AVKor, 2021-12-24
@AVKor

f = open('counter.txt','r')
a = int(f.read())
a+=1
f.close()
print(a)
f = open('counter.txt','w')
f.write(str(a))
f.close()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question