Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Check if files exists, If Yes Update it Else Create it [closed]

Tags:

python

file

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
like image 671
VeilEclipse Avatar asked Oct 18 '25 10:10

VeilEclipse


1 Answers

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))
like image 196
Tim Pietzcker Avatar answered Oct 20 '25 00:10

Tim Pietzcker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!