I am new to Python
I want to check if a filename checkzero.txt
exists
If it does not exists, I want to write 1 in checkzero.txt
, else I will increment it.
if os.path.exists("checkzero.txt"):
f = open('checkzero.txt', 'r')
counter = pickle.load(f)
f.close()
counter = counter + 1
f = open('checkzero.txt', 'w')
pickle.dump(counter, f)
f.close()
else:
f = open('checkzero.txt', 'w')
pickle.dump(1, f)
f.close()
However if I create checkzero.txt
as an empty file, it errors with:
Traceback (most recent call last):
File "FileBasics.py", line 8, in <module>
counter = pickle.load(f)
File "/usr/local/Cellar/python/2.7.2/lib/python2.7/pickle.py", line 1378, in load
return Unpickler(file).load()
File "/usr/local/Cellar/python/2.7.2/lib/python2.7/pickle.py", line 858, in load
dispatch[key](self)
File "/usr/local/Cellar/python/2.7.2/lib/python2.7/pickle.py", line 880, in load_eof
raise EOFError
EOFError
You need to open pickle
files in binary mode:
f = open('checkzero.txt', 'rb')
and
f = open('checkzero.txt', 'wb')
But why use pickle
at all?
You can get the same result like this:
try:
with open("checkzero.txt") as f:
counter = int(f.read()) +1
except IOError:
counter = 1
with open("checkzero.txt", "w") as f:
f.write(str(counter))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With