【发布时间】:2010-05-18 14:05:04
【问题描述】:
我知道这并不完全是 pickle 模块的用途,但我原以为这会起作用。我正在使用 Python 3.1.2
这是后台代码:
import pickle
FILEPATH='/tmp/tempfile'
class HistoryFile():
"""
Persistent store of a history file
Each line should be a separate Python object
Usually, pickle is used to make a file for each object,
but here, I'm trying to use the append mode of writing a file to store a sequence
"""
def validate(self, obj):
"""
Returns whether or not obj is the right Pythonic object
"""
return True
def add(self, obj):
if self.validate(obj):
with open(FILEPATH, mode='ba') as f: # appending, not writing
f.write(pickle.dumps(obj))
else:
raise "Did not validate"
def unpack(self):
"""
Go through each line in the file and put each python object
into a list, which is returned
"""
lst = []
with open(FILEPATH, mode='br') as f:
# problem must be here, does it not step through the file?
for l in f:
lst.append(pickle.loads(l))
return lst
现在,当我运行它时,它只打印出传递给类的第一个对象。
if __name__ == '__main__':
L = HistoryFile()
L.add('a')
L.add('dfsdfs')
L.add(['dfdkfjdf', 'errree', 'cvcvcxvx'])
print(L.unpack()) # only prints the first item, 'a'!
这是因为它看到了早期的 EOF 吗?也许附加仅适用于ascii? (在这种情况下,为什么让我做 mode='ba'?)有没有更简单的方法来做到这一点?
【问题讨论】:
-
我不知道pickle模块,我的python I/O有点生锈,但我猜你可能正在从文件中读取行,而对象存储时没有换行符分隔(实际上,其中可能包含换行符,因此如果是这种情况,您可能需要更改它)