• 3-2 优化购物车(文件实现)


     

     1.需求

    1.商品信息存在文件里面
    2.已购商品,余额记录,薪水,全部存在文件里面
    3.记录上次购物信息,下次不用输入薪水了
    4.用户,商家 两个python文件就行

    2.个人思路

     商家入口

    商品列表存到文件中,如何存?以什么形式存?
    
    如何读取出来?
    
    修改商品价格
    
    覆盖原来的文件
    

      

    用户接口

    已购商品列表放入文件 shopping_cart,
    
    薪水放入文件 salary,
    
    if  薪水文件有数据 
            
            打印文件中的商品列表
    
    else  输入新的薪水
    
    
    if  salary.isdigit():
            
            执行下一步
    
    
            选择的商品追加到shopping_cart
    
            最后的salary 放到 文件中
    

      

     3. 个人完整代码

    商家入口

     商品信息存入还是二维列表,

    import json
    while True:
        with open("goods.txt","r") as g:
            data = json.load(g)
            for index,item in enumerate(data):
                print(index,item)
    
            choice = input(">> which goods price  to change :")
            if choice.isdigit():
    
                if -1 < int(choice) < len(data):
                    print(data[int(choice)])
                    change_price = input("change it to >")
                    data[int(choice)][1] = int(change_price)
                    print('----change_after---
    ',data[int(choice)],'
    ')
                    with open("goods.txt","w") as g:
                        g.write(json.dumps(data))
    
            elif choice == 'q':exit()
            else:print("error you enter")
    

     

    goods.txt文件信息!  二维列表存入,读写都是二维列表格式的

    运行结果

    用户入口

    # coding=utf-8
    import json
    shopping_cart = []
    with open("salary") as f ,open("shopping_cart") as s_c:
    # f = open("salary",'r')
        user_salary = f.readline()
        shopping_cart_buy = s_c.readlines()
        # print(user_salary)
        # print(shopping_cart_buy)
    if user_salary:
        print("33[1m你还有¥%s人民币33[0m"%user_salary)
        if shopping_cart_buy:
            print("---you had buy --
    ",shopping_cart_buy)
    else:
        user_salary = input("your salary is :").strip()
    
    if user_salary.isdigit():
        salary = int(user_salary)
        while True:
            print('-----the list ----')
            with open('goods.txt','r') as g:
                data = json.load(g)
                for index,item in enumerate(data):
                    print(index,item)
    
            choice1 = input(">>>enter your choice :" )
            if choice1.isdigit():
                choice = int(choice1)
                if choice < len(data) and choice >= 0:
                    print('>>>your choice good is ',data[choice])
                    price = data[choice][1]
                    if price <= salary:
                        salary -= price
                        shopping_cart.append(data[choice])
                    else:
                        print("33[1m余额不足,your salary is %s33[0m"%salary)
                else: print("33[1menter error!!!33[0m")
            elif choice1 == 'q':
                break
            else: print("33[1menter error!!!33[0m")
    
        print('-----the shopping_cart ----')
        with open('shopping_cart','a+') as s_c:
            for i in shopping_cart:
                print(i)
                s_c.write(json.dumps(i))
        print('---------------------------
     your salary:',salary)
        with open('salary','w') as s:
            s.write(json.dumps(salary))
    else: print("33[1menter error!!!33[0m")
    

     

    薪水文件

    购物车文件

    商品文件

    运行结果

    4.个人心得

    4.1 文件指针问题

    文件读取f.readlines(),全部读完的时候,文件指针会到文件末尾,此时如果继续读文件的话,读的数据为0

        for line in goods.readlines():  #按行读取,把文件写到list列表中
    
            print(line)
    
            list.append(line.strip().split(','))
    

      

    4.2文件数据读出

    如何将数据读入list,或者字典中,然后对其进行操作

    list = []
    
    with open('goods1.txt','r+',encoding="utf-8") as goods:
    
        for line in goods.readlines():  #按行读取,把文件写到list列表中
            list.append(line.strip().split(','))
    
        for index,item in enumerate(list):
            print(index,item)
    
        choice = input(">> which goods price  to change :")
    

    最后如何把list 按照原来文件的格式保存覆盖到文件中去??  

    比如,list 最后是一个二维列表

    [["apple", 4888],["cake", 55]]
    

      

    4.3 json pickle 

    序列化和反序列化

    	• json,用于字符串 和 python数据类型间进行转换
    • pickle,用于python特有的类型 和 python的数据类型间进行转换

      

    可以保证文件数据读入写入都是数据的本身格式,二维list,dict,str

    数据如何存入文件?不影响其本身的类型,str,list,dict

    反序列化  json.load(f)

     将文件数据读出来

    import json
    while True:
        with open("goods.txt","r") as g:
    
            data = json.load(g)   #文件数据导入,数据的类型不变
    
            for index,item in enumerate(data):
                print(index,item)
    

    运行结果

    序列化

    最后data 二维列表的数据存入文件中

     with open("goods.txt","w") as g:
                        g.write(json.dumps(data))
    

      

    将购物车信息,薪水信息,追加到文件中

       with open('shopping_cart','a+') as s_c:
            for i in shopping_cart:
                s_c.write(json.dumps(i))
    
        with open('salary','w') as s:
            s.write(json.dumps(salary))
    

      

    4.4 错误演示

     程序1

    文件 二维列表

    import json
    with open("goods.txt","r") as g:
        data = json.load(g)
        for index,item in enumerate(data):
            print(index,item)
    

      

     程序2

    文件  只是单独的列表放进去,不是二维列表

    import json
    with open("shopping_cart",'r') as s_c:
        
        data = json.load(s_c)
    
        for index,item in enumerate(data):
            print(index,item)
    

      

     

     4.5 数据格式 文件

    文件读入和读取,数据的格式是否变化,是否影响文件的改变,还是存在很大的不解!

     

    
    
    
    
    
    
  • 相关阅读:
    转载:MyBatis获取插入记录的自增长字段值
    006---抽象类
    005---组合
    004---继承与派生
    003---属性查找和绑定方法
    002---类与对象
    001---面向对象和面向过程的区别
    017---Django的中间件解决跨域
    10---git安装
    007---归并排序
  • 原文地址:https://www.cnblogs.com/venicid/p/7246929.html
Copyright © 2020-2023  润新知