我知道這不是醃製模塊是如何使用的,但我原以爲這會起作用。我使用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'?)有沒有更簡單的方法來做到這一點?
我不知道泡菜模塊和我的蟒蛇I/O是一個有點生疏,但我的猜測是,你或許讀取來自線文件,而對象存儲沒有換行符分隔(事實上,可能包含換行符,因此如果是這種情況,您可能需要更改它) – falstro 2010-05-18 14:08:26