最近学习python的时候写了一个小demo用来练手,是用text文件来存储商品信息和自己余额的。
commodity = []
count = 0
exit_falg = True
yu = 0
try:
with open("F://balance.txt", "r+", encoding="UTF-8") as balance:
for b in balance:
yu = int(b)
if yu == 0:
yu = int(input("请输入工资:"))
balance.write(str(yu))
break
balance.close()
if yu != 0:
with open("F://product_information.txt", "r+", encoding="UTF-8") as data:
for each_lines in data:
c = []
(name, price) = each_lines.split(":", 1) # split(':', 1)处理多个冒号的情况,只分一次
# print(count, name, price.strip())
c.append(count)
c.append(name)
c.append(int(price.strip()))
commodity.append(c)
count += 1
data.close()
while exit_falg:
for i in commodity:
print(i)
choice = input("输入要购买的商品:")
if choice.isdigit():
if int(choice) >= 0 or int(choice) <= len(commodity): # 输入商品编号 正确
if commodity[int(choice)][2]<=yu:
yu -= commodity[int(choice)][2] #产品金额减去当前余额,并同步到text文件中
with open("F://balance.txt", "w+", encoding="UTF-8") as balance2:
balance2.write(str(yu))
balance2.close()
print("付款成功!")
else:
print("余额不足,付款失败!!!")
else:
print("该商品不存在")
elif choice == "q":
exit_falg = False
else:
print("输入不正确请重新输入!")
except IOError as io:
print(io)
下面是text文件的商品信息
下面是价格,默认为0,不可以为空