'''
购物车程序
用户入口:
1.商品信息存在文件里
2.已购商品,余额记录
商家入口:
1.可以添加商品,修改商品价格
'''
filePath = "D:\Python_work\Lpython\day2\shoppinglist.txt"
with open (filePath, "r") as f:
filetext = f.readlines()
k = len(filetext)
# print(filetext)
# 提取商品列表(将字符串以逗号分割写入列表)
fileList = []
for i in range(k):
c = filetext[i].split(",")
fileList.append([c[0],int(c[1])])
print(fileList)
# ================
# 用户入口
# ================
fileLen = len(fileList)
salary = int(input("请输入您的工资: "))
for j in range(fileLen):
# 打印商品(编号,商品名称,价格)
print(j, '.', fileList[j][0], ' ', fileList[j][1])
shoppingList = []
while True:
selectNum = input("请选择商品编号:")
if selectNum.isdigit():
selectNum = int(selectNum)
if 0 <= selectNum < fileLen:
p_item = fileList[selectNum]
if p_item[1] <= salary:
shoppingList.append(p_item)
salary -= p_item[1]
print("已添加 %s 商品到购物车,您的余额为:\033[31;0m %s \033[0m" % (p_item, salary))
else:
print("\033[41;1m你的余额只剩[%s]啦,还买个毛线啊 \033[0m" % salary)
for going in shoppingList:
print("您已购商品为: ", going)
print("您当前的余额为: ", salary)
break
else:
print("您选择的 [%s] 不存在,请重新选择 " % selectNum)
elif selectNum == "q":
print("---------shopping list---------")
for going in shoppingList:
print("您已购商品为: ", going)
print("您当前的余额为: ", salary)
exit()
else:
print("无效选项")
# ================
# 商家入口
# ================
goodskey = dict(fileList)
print(goodskey)
# 修改商品名称 & 修改价格 & 添加商品
goodskey["Iphone11"] = "5999"
goodskey.update({'Iphone12':goodskey.pop("Iphone11")})
print(goodskey)
with open(filePath, 'w+') as f:
for key in goodskey: # for key,value in goodskey.items(): 不建议这样写
f.write('{0},{1}\n'.format(key,goodskey[key]))
# 添加商品
with open (filePath, "a+") as f:
f.write("Python8,8800\n")