[英]Error is being shown when I run the code and I am unable to figure out the second question
import pickle
med = {}
medfile = open("Medicines.dat","wb")
while True:
name = input("Enter the name: ")
company = input("Enter the company: ")
chemical = input("Enter the chemical: ")
price = input("Enter the price: ")
med['name'] = name
med['company'] = company
med['chemical'] = chemical
med['price'] = price
pickle.dump(med,medfile)
ans = input("Wouldyou like to add more(y/n) ")
if ans == "y":
continue
elif ans == "n":
break
medfile = open("Medicines.dat","r+")
print(pickle.load(medfile))
medfile.close()
問題如下: 一個二進制文件“Medicines.dat 的結構為 [Name, Company, Chemical, Price] a) 編寫一個用戶定義的 function add_data() 來輸入記錄數據並存儲在文件中 b) 編寫一個function search() 接受公司名稱並顯示該公司所有葯品的詳細信息
這里有幾個問題:
medfile = open("Medicines.dat","r+")
你的意思是rb
。 此處解釋了差異,但 pickle 解析要求文件處於“二進制”模式,因此是“b”。
作為最佳實踐,您應該在重新打開文件進行寫入之前關閉文件。 ( medfile.close()
)。 更好的是,如果您使用“with”語法創建上下文,python 將處理文件何時關閉
雖然代碼現在應該可以運行,但我懷疑它是否會執行您想要的操作。 您的查詢詢問“Would you [sic] like to add more(y/n)”,但在我看來它並不像添加更多值,因為您一遍又一遍地使用相同的“med”字典。 考慮如何根據鍵將“新”字段與“舊”字段區分開來
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.