我是 Python 新手
我想检查文件名是否checkzero.txt
存在
如果它不存在,我想在 中写 1 checkzero.txt
,否则我会增加它。
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()
但是,如果我创建checkzero.txt
为空文件,则会出错:
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