ver 1.0

  • 进行第二代系统写入时,首先考虑的是数据存储,这一次用外界的文本文档进行解决,导入了json模块;
  • 同时,学习了函数的封装,所以这次把函数进行了封装,封装成独立的模块。 ```python “”” 超市蔬菜查询系统 author:wd date:20200219 version:1.0
    1. 蔬菜价格查询系统
    2. 未有产品的录入系统,要求循环输入,直到输入特定字符退出
    3. 使用自定函数的方法重新编码 “””

      将蔬菜字典录入文本文档

      import json

      def init(data):

      # data = {}

      js = json.dumps(data)

      file = open(‘mypy_08_02’, ‘w’)

      file.write(js)

      file.close()

蔬菜字典检索系统(检测有无,如果没有则返回None)

def lookup(vegetables): file = open(‘mypy_08_03’, ‘r’) js = file.read() data = json.loads(js) file.close() return data.get(vegetables)

蔬菜增加系统(先检索在不在,如果不在,增加字典后再写入)

def add(vegetable, price):

file = open(‘mypy_08_03’, ‘r+’)

js = file.read()

data = json.loads(js)

data[vegetable] = price

file.close()

def add(vegetable, price): file1 = open(‘mypy_08_03’, ‘r’) js = file1.read() data = json.loads(js) file1.close()

  1. file2 = open('mypy_08_03', 'w')
  2. data[vegetable] = price
  3. jsl = json.dumps(data)
  4. file2.write(jsl)
  5. file2.close()

vegetable = input(‘请输入您要找的蔬菜:’) if lookup(vegetable): print(lookup(vegetable)) else: price = int(input(‘请输入蔬菜的价格:’)) add(vegetable, price) print(‘录入完成!’)

else:

price = int(input(‘请输入产品的价格:’))

file = open(‘mypy_08_02’, ‘w’)

js = file.read()

data = json.loads(js)

data[vegetables]= price

```