python-商品管理:在txt文件中管理

需求:商品管理

        choice = input('请输入你的选择:')

        1、添加商品  def add_product():

           商品名称:商品已经存在的话,要提示

            商品价格: 校验,是大于0的数字

            商品数量:校验,只能是大于0的整数

        2、删除商品  def del_product():

            商品名称:商品不存在的话,要提示

        3、查看商品 def show_product():

            显示所有的商品信息

        4、退出

    思路:商品存入字典里,然后以json串的形式写入文件

import json

#新的商品写入文件:json串(字符串)写入文件
def write_json(dic):
    fw=open('user.json','w',encoding='utf-8')
    # 字典转字符串 indent 缩进4个字符串 ensure_ascii=False中文乱码
    json.dump(dic,fw,indent=4,ensure_ascii=False)
    fw.close()

#读取文件中的商品:读取文件中的json串
def read_json():
    fr=open('user.json','r',encoding='utf-8')
    res=fr.read()
    if res :
        res = json.loads(res)  # loads() 字符串转字典
    else:
        res={}
    return res

#价格校验(大于0的数字,包括正整数和正小数)
def ispositivenumber(n):
    n=str(n)
    if n.count('.')==1:
        left,right=n.split('.')
        if left.isdigit() and right.isdigit():
            return float(n)
    elif n.isdigit() and n!=0:
        return int(n)
    return False

#数量校验(大于0的整数)
def ispositiveinteger(n):
    n=str(n)
    if n.isdigit() and n!=0:
        return int(n)
    else:
        return False

#添加商品
def add_product():
    name=input("输入要添加的商品的名称:").strip()
    price=input("输入商品价格:").strip()
    number=input("输入商品数量:").strip()
    all_products=read_json()
    #非空即真
    if not name or not price or not number:
        print("输入不能为空")
    elif name in all_products:
        print("商品已存在,无须重复添加!")
    elif not ispositivenumber(price):
        print("输入商品价格不合法,只能是大于0的数字!")
    elif not ispositiveinteger(number):
        print("商品数量不合法,只能是大于0的整数")
    else:
        all_products[name]={"price":float(price),"number":int(number)} #字典类型:增加k=v
        write_json(all_products)
        print("添加成功!")
        # return
    return add_product() #递归,自己调用自己

#删除商品
def del_product():
    name=input("输入要删除的商品名称:").strip()
    all_products = read_json()
    if not name:
        print("输入商品名称为空!")
    elif not name in all_products:
        print("商品不存在!")
    else:
        all_products.pop(name) #字典类型:删除
        write_json(all_products)
        print("删除商品成功!")

#查看所有商品
def show_product():
    res=read_json()
    if res:
        print(res)
    else:
        print("暂时还没有商品!")

choice = input('请输入你的选择[1:添加商品;2:删除商品;3:展示商品;4:退出]:')
func_map={"1":add_product,"2":del_product,"3":show_product,"4":quit} #函数相当于一个变量
if choice in func_map:
    func_map[choice]()
else:
    print("输入有误!")
 
原文地址:https://www.cnblogs.com/you-me/p/10160394.html