# import collections
import os
def readFile(file,modle):
#判断文件是否存在
if os.path.exists(file) :
bf = open(file,modle)
res = bf.read()
bf.close()
return res
else :
return None
def saveFile(file,res):
gf = open(file, "w")
gf.write(res)
gf.close()
def bussessFun():
# eval 讲类型的字符串转为类型
res = readFile("goods", "r")
goods = {}
if res :
#将字典类型的字符串转为字典
goods = eval(res)
print(goods)
# print(res)
# print(goods)
#修改商品价格
# goods['iphoneX'] = 7000
# #添加个商品
# goods['watch'] = 5600
#这里做成商家输入
while True:
goodsname = input("input goodsname if you want to exit input q:")
if 'q' == goodsname :
break
price = int(input("input %s price :"%goodsname))
#商品存在,修改价格,商品不存在,保存商品
goods[goodsname] = price
#循环结束,保存商品
saveFile("goods",str(goods))
def consumer():
res = readFile("goods", "r")
goods = {}
if res:
goods = eval(res)
if len(goods) == 0 :
print("has no goods")
exit()
#查询已买的商品
hasBuy = readFile("hasBuy","r")
if not hasBuy:
hasBuy = []
else:
#将列表类型的字符串转为列表
hasBuy = eval(hasBuy)
moneys = {}
moneyres = readFile("money", "r")
if moneyres:
moneys = eval(moneyres)
if "money" not in moneys:
#展示所有的商品和价格,以及所在的编号,因为字典是无序的这里使用列表
#百度的方法,使用collections模块,变成有序字典
# z = collections.OrderedDict(goods)
# print(z)
#每次购买完后退出程序,需要将余额保存下来
money = int(input("input your money:"))
else:
money = moneys.get("money")
#这里使用字符串的方法转为列表
goods = str(goods).strip("{").strip("}").split(",")
# print(goods)
# hasBuy = hasBuy.split(",")
for i,v in enumerate(goods):
print(i,v)
while True:
index = input("input you want to buy:,if 'q' exit:")
if index.isdigit():
index = int(index)
if index < len(goods) and index >= 0:
#将买的商品和价格
goodsprice = goods[index]
# print(goodsprice.split(":")[1])
price = int(goodsprice.split(":")[1])
if price < money :
money -= price
hasBuy.append(goodsprice)
else:
print("you don't have enough mmoney")
elif 'q' == index:
break
else:
pass
#购买结束,将余额和购买的商品保存下来
moneys["money"] = money
saveFile("money", str(moneys))
saveFile("hasBuy", str(hasBuy))
consumer();