标签:今天 manage with let 建议 根据 删除 split lan
今天写着购物车的作业,最头疼的是文件操作了
尤其是文件的打开模式 w r a 最TM的头疼
r+模式可读可写,但是写的内容会根据文件指针去覆盖之前的内容,当文件需要修改时,强烈建议不要用这种模式,会有一个坑
下面说说文件的思路吧,还没有学习函数,因此代码起来很乱
1.设置接口
#user接口
if ident_flag == ‘u‘:
首先读入文件的数据
# 商品信息 with open("goods.txt",‘r‘) as goods_file: goods_info = {} for line in goods_file.readlines(): item = line.strip(‘\n‘).split(‘ ‘) goods_info[item[0]] = item[1] # 余额信息 with open("balance.txt",‘r‘) as balance_file: balance = int( balance_file.readline().strip(‘\n‘) )
购买商品
# 购买商品 buy_name = input("Which goods would your like to buy?(input the name of goods)>>: ") if buy_name in goods_info: if balance > int( goods_info[buy_name] ): balance = balance - int( goods_info[buy_name] ) shopping_list[buy_name] = goods_info[buy_name] else: print("I‘m sorry to hear that you have not enough money to buy this") else: print("Sorry sir, there is not the goods that you need!!\n")
结账
# 结算 with open("balance.txt",‘w‘) as goods_file: goods_file.write(str(balance))
#manager接口
elif ident_flag == ‘m‘:
首先读入文件
# 商品信息 with open("goods.txt",‘r‘) as goods_file: goods_info = {} for line in goods_file.readlines(): item = line.strip(‘\n‘).split(‘ ‘) goods_info[item[0]] = item[1]
增加商品
# 增加商品 if choice == ‘a‘: print("you are adding a goods".center(50,‘-‘)) goods_name = input("The goods_name is: ") goods_price = input("The goods_price is: ") print("\n".rjust(51,‘-‘)) info = goods_name + ‘ ‘ + goods_price + ‘\n‘ with open("goods.txt", ‘a‘) as goods_file: goods_file.write(info)
修改商品
# 修改商品 elif choice == ‘m‘: print("You are modify a goods".center(50, ‘-‘)) goods_name = input("The goods_name is: ") if goods_name in goods_info: goods_price = input("The goods_price is: ") goods_info[goods_name] = goods_price with open("goods.txt", ‘w+‘) as goods_file: for item in goods_info: info = item + ‘ ‘ + goods_info[item] + ‘\n‘ goods_file.write(info) else: print("Sorry sir, there is not -{_goods_name}-!".format(_goods_name = goods_name))
删除商品
# 删除商品 elif choice == ‘d‘: print("you are delete a goods".center(50, ‘-‘)) goods_name = input("The goods_name is: ") if goods_name in goods_info: goods_info.pop(goods_name) with open("goods.txt",‘w‘): for item in goods_info: info = item + ‘ ‘ + goods_info[item] + ‘\n‘ goods_file.write(info)
标签:今天 manage with let 建议 根据 删除 split lan
原文地址:http://www.cnblogs.com/JackyPeng/p/6883666.html