【发布时间】:2015-08-10 09:13:54
【问题描述】:
我想使用 pickle 来保护一些字符串并将昨天的字符串与今天的字符串进行比较。
filename = filename + '_yesterday.txt'
with open(filename, 'w+') as myfile:
# if empty write something
if os.path.getsize(myfile) == 0:
myfile.write('write something')
old_strings = pickle.load(myfile)
all_strings = '....'
with open(filename, 'w') as myfile:
pickle.dump(all_strings, myfile)
第一个问题:为什么我不能为文件使用 var-name 我总是遇到这个异常。
with open(filename, 'w+') as myfile:
IOError: [Errno 2] No such file or directory:
第二个问题: 如果我将它与现有文件一起使用,则会出现此异常:
if os.path.getsize(myfile) == 0:
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/genericpath.py", line 49, in getsize
return os.stat(filename).st_size
TypeError: coercing to Unicode: need string or buffer, file found
【问题讨论】:
-
你的缩进是否正确
-
@VigneshKalai 抱歉,现在它是正确的。
-
你能打印文件名吗
-
python 2 还是 3?我认为您使用 unicode 文件名
-
@VigneshKalai 已经完成,很好。我将代码简化为: with open('test.txt', 'r') as myfile: old_str = pickle.load(myfile) - 它仍然无法解决我得到: File "/System/Library/Frameworks /Python.framework/Versions/2.7/lib/python2.7/pickle.py”,第 1378 行,在加载返回 Unpickler(file).load() 文件“/System/Library/Frameworks/Python.framework/Versions/2.7 /lib/python2.7/pickle.py”,第 858 行,在加载调度 [key](self) 文件“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py ",第 880 行,在 load_eof 中引发 EOFError EOFError