- 将蔬菜字典录入文本文档
- def init(data):
- # data = {}
- js = json.dumps(data)
- file = open(‘mypy_08_02’, ‘w’)
- file.write(js)
- file.close()
- 蔬菜字典检索系统(检测有无,如果没有则返回None)
- 蔬菜增加系统(先检索在不在,如果不在,增加字典后再写入)
- def add(vegetable, price):
- file = open(‘mypy_08_03’, ‘r+’)
- js = file.read()
- data = json.loads(js)
- data[vegetable] = price
- file.close()
- else:
- price = int(input(‘请输入产品的价格:’))
- file = open(‘mypy_08_02’, ‘w’)
- js = file.read()
- data = json.loads(js)
- data[vegetables]= price
ver 1.0
- 进行第二代系统写入时,首先考虑的是数据存储,这一次用外界的文本文档进行解决,导入了json模块;
- 同时,学习了函数的封装,所以这次把函数进行了封装,封装成独立的模块。 ```python “”” 超市蔬菜查询系统 author:wd date:20200219 version:1.0
蔬菜字典检索系统(检测有无,如果没有则返回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()
file2 = open('mypy_08_03', 'w')
data[vegetable] = price
jsl = json.dumps(data)
file2.write(jsl)
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
```