首页 > 解决方案 > 运行代码时显示错误,我无法弄清楚第二个问题

问题描述

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) 编写一个用户定义的函数 add_data() 来输入一条记录的数据并存储在文件中 b) 编写一个函数 search() 接受公司名称并显示该公司所有药品的详细信息

标签: python

解决方案


这里有几个问题:


1、正确打开文件

medfile = open("Medicines.dat","r+")

你的意思是rb此处解释了差异,但pickle解析要求文件处于“二进制”模式,因此是“b”。


2正确关闭文件

作为最佳实践,您应该在重新打开文件进行写入之前关闭文件。( medfile.close())。更好的是,如果您使用“with”语法创建上下文,python 将处理文件何时关闭


3、拥有正确的价值观

虽然代码现在应该运行,但我怀疑它会做你想要的。您的查询询问“您 [原文如此] 是否愿意添加更多(y/n)”,但在我看来它不像添加更多值,因为您一遍又一遍地使用相同的“med”字典。考虑“新”字段如何与“旧”字段区分开来,基于它们的键


推荐阅读