#coding=utf8
'''
1、实现一个商品管理的程序。
# 输出1,添加商品 2、删除商品 3、查看商品
添加商品:
商品的名称:xxx
商品如果已经存在的话,提示商品商品已经存在
商品的价格:xxxx
数量只能为大于0的整数
商品的数量:xxx,数量只能为大于0的整数
2、删除商品:
输入商品名称:
iphone
如果输入的商品名称不存在,要提示不存在
3、查看商品信息:
输入商品名称:
iphone:
价格:xxx
数量是:xxx
all:
print出所有的商品信息
'''
import json
'''
添加商品:
商品的名称:xxx
商品如果已经存在的话,提示商品商品已经存在
商品的价格:xxxx
数量只能为大于0的整数
商品的数量:xxx,数量只能为大于0的整数
'''
def add_prodect(fileName):
info = {"phone" : {"product_price":11,"product_count" : 1}}
with open(fileName,'r+',encoding='utf-8') as file: #必须使用 r+ 先读后写模式
file.seek(0)
fr = file.read()
product_dict=json.loads(fr) # 这里必须取出数据转成dict格式 否则后续添加商品有问题
# print(product_dict)
#定义一个空字典,用户存放商品
product_name = input('请输入你要添加商品的名称:').strip()
product_price = input('请输入商品的价格:').strip()
product_count = input('请输入商品的数量:').strip()
if not (product_price.isdigit() or product_count.isdigit()):
print('输入的价格或者数量不合法')
elif int(product_count)<=0:
print('数量只能为大于0的整数')
elif product_name in product_dict:
print('商品商品已经存在')
else:
new_dict = {} #定义新的字典 存放你输入的数据
new_dict[product_name]={'product_price':product_price,'product_count':product_count} #定义新的字典格式
product_dict.update(new_dict) #添加到你取出字典中,有就更新,没有增加
print(product_dict)
file.seek(0)
file.write(json.dumps(product_dict)) #这里必须使用json.sumps格式添加,,否则添加后的数据格式不否
print('商品添加成功')
# add_prodect('shopping.txt')
'''
2、删除商品:
输入商品名称:
iphone
如果输入的商品名称不存在,要提示不存在
'''
def del_product(fName):
with open(fName,'a+',encoding = 'utf-8') as f:
f.seek(0)
fr = f.read()
fr_dict = json.loads(fr) #讲文件中的内容转换成字典
print(fr_dict)
product_name = input('请输入你要删除的商品名称').strip()
if len(fr_dict) > 0:
if product_name not in fr_dict :
print('商品名称不存在')
else:
del fr_dict[product_name]
f.flush()
print('删除成功')
print(fr_dict)
f.seek(0)
f.truncate()
f.write(json.dumps(fr_dict,indent=4,ensure_ascii=False))
else:
print('空空如也,无东西可删')
# del_product('shopping.txt')
'''
3、查看商品信息:
输入商品名称:
iphone:
价格:xxx
数量是:xxx
all:
print出所有的商品信息
'''
def product_check(file):
with open(file,encoding='utf-8') as f1:
fr = f1.read()
load_fr_dict = json.loads(fr)
print(load_fr_dict)
product_info = input('请输入你要查看的商品名称,all表示全部:')
if load_fr_dict:
if product_info == 'all':
print(load_fr_dict)
elif product_info not in load_fr_dict:
print('商品不存在')
else:
print('商品{0}:\n价格是:{1}\n数量是:{2}'.format(product_info,
load_fr_dict[product_info]['product_price'],
load_fr_dict[product_info]['product_count']))
else:
print('商品表空空如也')
# product_check('shopping.txt')
def function_product(file):
flag = int(input('请输入你要进行的动作,1:添加商品 2:删除商品 3:查看商品\n'))
if flag == 1:
add_prodect(file)
elif flag == 2:
del_product(file)
elif flag == 3:
product_check(file)
else:
print('只能输入数字 且 1:添加商品 2:删除商品 3:查看商品')
filename ='shopping.txt'
function_product(filename)