'Save dictionary to file Python Tkinter
first-time poster/ new to coding, working with Python3, Tkinter, and Pickle.
For a project I'm working on I have designed a random meal generator that uses user input ingredients and determines what meals are available to be cooked. Everything is functional with the exception of being able to save and open the ingredient dictionary.
Basically what I want is for a user to be able to save their ingredients and open that file using filedialog.
Here is a sample code of what I have written for saving the recipe list:
def save_Recipe():
file_name = filedialog.asksaveasfilename(initialdir="""C:/Users/tanne/Desktop/Coding_Exes/Foodomizer_lists/Recipe_List""", title= "Save File", filetypes=(("Dat Files", "*.dat"),("All Files", "**")))
if file_name:
if file_name.endswith(".dat"):
pass
else:
file_name = f"{file_name}.dat"
# Grab all stuff from recipe list
lrl= len(recipe_list)
stuff = recipe_list[0:lrl]
# Open the file
output_file = open(file_name, "wb")
# Actually add the stuff to the file
pickle.dump(stuff, output_file)
def open_Recipe():
file_name = filedialog.askopenfilename(initialdir= """C:/Users/tanne/Desktop/Coding_Exes/Foodomizer_lists/Recipe_List""", title= "Open File", filetypes=(("Dat Files", "*.dat"), ("All Files", "**")))
if file_name:
# Delete currently open list
display_recipe.delete(0,END)
#Open the file
input_file = open(file_name, "rb")
#Load the data from the file
stuff = pickle.load(input_file)
#Output stuff to the screen
n = 0
for item in stuff:
if item not in recipe_list:
recipe_list.insert(n, item)
n += 1
display_recipe_update()
These functions are accessed through menu buttons. But I cannot figure out how to do the same with my ingredients dictionary. Example = {ingredient_name : num_of_ingredient}, {Bread:2, Cheese: 1}.
def save_ingredients():
global ingredients
global stuff2
file_name = filedialog.asksaveasfilename(initialdir="""C:/Users/tanne/Desktop/Coding_Exes/Foodomizer_lists/Ingredients_Dic""", title= "Save File", filetypes=(("Dat Files", "*.dat"),("All Files", "**")))
if file_name:
if file_name.endswith(".dat"):
pass
else:
file_name = f"{file_name}.dat"
# Grab all stuff from ingredients
stuff2 = ingredients.get(0,END)
input_file = open(file_name, 'wb')
pickle.dump(stuff2, input_file, protocol=pickle.HIGHEST_PROTOCOL)
input_file.close()
def open_ingredients():
file_name = filedialog.askopenfilename(initialdir= """C:/Users/tanne/Desktop/Coding_Exes/Foodomizer_lists/Ingredients_Dic""", title= "Open File", filetypes=(("Dat Files", "*.dat"), ("All Files", "**")))
if file_name:
# Delete currently open list
input_file = open(file_name, 'rb')
output_file = pickle.load(input_file)
print(output_file)
input_file.close()
What I want to happen is for the saved file to contain all of the information in the dictionary as it is. This is an example of my test ingredients dictionary.
ingredients = {"Bun": 1, "Beef Patty": 1, "Lettuce": 1, "Cheese": 1, "Tomatoe": 1, "Pizza Crust": 1, "Tomatoe Sauce": 1, "Pork" : 2, "Basil": 1, "Rice": 1, "Bread": 2}
The program uses this dictionary in several functions to determine which recipes (personally made class objects) are available. It does this by going through the ingredient dictionary, finding the key that matches with the ingredients stored in the recipe, and seeing the value of the key is >= the number of ingredients needed in the recipe.
What is happening with saving and opening the dictionary is that I can save the file and open the file without any errors. But when I print the ingredients dictionary it is still empty.
My question is how do I save a dictionary to a file and then when I open that file the dictionary will be populated with whatever I saved in the file?
I've been looking through stackoverflow for two days trying everything that I can see but none of it is working. Any suggestions would greatly be appreciated!
Solution 1:[1]
As far as I can see, your code for storing and reading data should be fine. As @Pepsi-Joe suggests, you could use JSON instead of pickle to save the data to disk because it's safer and more portable than pickle. Another suggestion is to generally use a with statement to open files to avoid stale file handles, for example:
with open("/path/to/file", 'r') as fh:
data = fh.readlines()
To debug this issue, I suggest you open an interactive Python console, read and store the file. Or use a debugger to see what's the written (stuff2) and read content. Maybe it's a bug in your UI code?
If your ingredients are as you describe, I suppose that ingredients.get(0, END) could return None, which is then saved to the file. So, the file contains "nothing", which you get back when you read it. Just delete that line and save ingredients directly should be fine.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
