Warum funktioniert das Anhängen von Binary Pickles nicht?
Ich weiß, dass das Pickle-Modul nicht genau so verwendet werden sollte, aber ich hätte gedacht, dass dies funktionieren würde. Ich verwende Python 3.1.2
Hier ist der Hintergrundcode:
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
Nun, wenn ich es ausführe, druckt es nur das erste Objekt aus, das an die Klasse übergeben wird.
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'!
Ist das, weil es eine frühe EOF sieht? Vielleicht ist das Anhängen nur für Ascii gedacht? (In welchem Fall lässt es mich mode = 'ba' machen?) Gibt es einen viel einfacheren Weg, dies zu tun?