Reputation: 39
I'm creating a very basic program that stores a dictionary of words translated from English to French, for example :
I'm storing all those values in a file that I append and read using the pickle function.
The problem is that when I use pickle.load to read the file and then print it, only the first value is returned.
I can't see where is my error, and I've been looking everywhere without getting any answer. Thanks in advance.
import pickle
import os
clear=lambda:os.system("cls")
def pause():
input("Press ENTER to continue.")
def print_dictionary(dct):
print("Dictionary (English / French)")
for wordenglish, wordfrench in dct.items():
print("{} : {}".format(wordenglish, wordfrench))
dictionary={}
for loop in range(3):
wordEnglish=input("Enter the word in English : ")
wordFrench=input("Enter the word in French : ")
pause()
clear()
print("Saving ...")
dictionary[wordEnglish]=wordFrench
with open("data","ab") as file:
pickler=pickle.Pickler(file)
pickler.dump(dictionary)
print("Saved !")
pause()
with open("data","rb") as file:
unpickler=pickle.Unpickler(file)
dictionary_get=unpickler.load()
print_dictionary(dictionary_get)
pause()
For example, if I enter "Fire","Feu" / "Water","Eau" / "Mud","Boue", the only value I will get will be "Fire","Feu".
Upvotes: 0
Views: 2135
Reputation: 6107
Now you can use the walrus operator (:=) in a clear way:
with open('pickle_file_to_read.p', 'rb') as f:
pickler = pickle.Unpickler(f)
while record := pickler.load():
# record is the read object from the pickle file.
Upvotes: 0
Reputation: 11
use exception like
try:
while True:
y=pickle.load(file)
print(y)
except EOFError:
print('End of File')
Upvotes: 1