第一次發帖/編碼新手,使用 Python3、Tkinter 和 Pickle。
對于我正在處理的一個專案,我設計了一個隨機膳食生成器,它使用用戶輸入的成分并確定可以烹飪哪些膳食。除了能夠保存和打開成分字典外,一切都正常。
基本上我想要的是用戶能夠保存他們的成分并使用檔案對話框打開該檔案。
這是我為保存食譜串列而撰寫的示例代碼:
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()
這些功能可通過選單按鈕訪問。但我不知道如何對我的配料字典做同樣的事情。示例 = {ingredient_name:num_of_ingredient},{面包:2,奶酪: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!
uj5u.com熱心網友回復:
保存 a 的最簡單方法dict是使用json
import json
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}
filename = 'path/to/file.txt'
#save file
with open(filename, 'w') as f:
f.write(json.dumps(ingredients))
#load file
with open(filename, 'r') as f:
ingredients_from_file = json.load(f)
json還具有人類可讀的優勢,這應該可以幫助您診斷代碼中的任何錯誤。
uj5u.com熱心網友回復:
據我所知,您用于存盤和讀取資料的代碼應該沒問題。正如@Pepsi-Joe 建議的那樣,您可以使用 JSON 而不是 pickle 將資料保存到磁盤,因為它比 pickle 更安全、更便攜。另一個建議是通常使用with陳述句打開檔案以避免過時的檔案句柄,例如:
with open("/path/to/file", 'r') as fh:
data = fh.readlines()
要除錯此問題,我建議您打開一個互動式 Python 控制臺,讀取并存盤該檔案。或者使用除錯器查看寫入的內容 ( stuff2) 并讀取內容。也許這是您的 UI 代碼中的錯誤?
如果您ingredients是您所描述的,我想ingredients.get(0, END)可能會回傳None,然后將其保存到檔案中。因此,該檔案包含“無”,您在閱讀時會回傳。只需洗掉該行并ingredients直接保存就可以了。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/422089.html
標籤:
