Python-文件操作-之优化购物车
#此次购物车优化,主要使用了文件操作的相关方法,有买家入口,和商家入口
一、买家入口
1、买家第一次启动程序输入金额,金额会记录到文件里,再登录就读取文件里保存的金额,买家可以购买商品,按 ‘q’ 退出后显示购买的商品和余额,并保存购买过的商品和余额。
1 global data 2 global userinformation 3 money='' 4 data='data.txt' 5 userinformation='userinformation.txt' 6 mgoods=[] 7 exit_flag = False 8 def shuoppxit(money): 9 if money.isdigit(): 10 while not exit_flag: 11 for index, item in enumerate(goods): 12 print(index, item) 13 numbres = input("输入购买商品的序号:") 14 if numbres.isdigit(): 15 numbres = int(numbres) 16 if numbres< len(goods) and numbres >=0: 17 money = int(money) 18 numbres_goods=goods[numbres][1] 19 if money >= numbres_goods: 20 money=money-numbres_goods 21 goods[numbres].append('余额') 22 goods[numbres].append(money) 23 print(goods[numbres]) 24 mgoods.append(goods[numbres]) 25 f = open(userinformation, 'w+', encoding='utf-8') 26 f.write(str(mgoods)) 27 f.close() 28 print('购买商品成功:'+goods[numbres][0]) 29 print('剩余金钱:\033[31;1m %s \33[0m' % money ) 30 else: 31 print('余额不足!') 32 elif numbres=='q' or numbres=='Q': 33 print('你购买的商品如下:') 34 f = open(userinformation, 'r', encoding='utf-8') 35 data2 = f.read() 36 goods2 = eval(data2) 37 for i in goods2: 38 print(i) 39 break 40 else: 41 print('输入错误!!') 42 else: 43 print('输入错误!!,重新输入') 44 45 f = open(data,'r',encoding='utf-8') 46 data2 = f.read() 47 goods = eval(data2) 48 49 f = open(userinformation,'r',encoding='utf-8') 50 data2 = f.read() 51 if data2 !='': 52 usernames = eval(data2) 53 money= usernames[0][3] 54 money=str(money) 55 shuoppxit(money) 56 else: 57 money = input("输入你的钱:") 58 shuoppxit(money)
二、商家入口
1、商家可以添加商品,和修改商品价格
global data money='' data='data.txt' mgoods=[] exit_flag = False f = open(data,'r',encoding='utf-8') data2 = f.read() goods = eval(data2) print(goods) while not exit_flag: choice=input('1、添加商品 2、修改价格:') if choice.isdigit(): if choice=='1': name=input('输入商品名:') price=input('输入价格:') mgoods.append(name) mgoods.append(price) goods.append(mgoods) f = open(data, 'w', encoding='utf-8') f.write(str(goods)) f.close() print(goods) else: for index, item in enumerate(goods): print(index, item) numbres = input("输入修改商品的序号:") if numbres.isdigit(): numbres = int(numbres) if numbres < len(goods) and numbres >= 0: jiage = input("输入修改商品价格:") if jiage.isdigit(): jiage = int(jiage) goods[numbres][1]= jiage f = open(data, 'w', encoding='utf-8') f.write(str(goods)) f.close() print(goods) exit_flag=True
学习无止境,加油