- 需要掌握open函数。
- 清单存取时,需要注意编码问题,直接在读取和存储时加上encoding = 'utf - 8' 可以解决gbk - unicode转化时出现的乱码问题。
# _*_coding:utf-8_*_
import os
FILE_PATH = 'save.txt'
# Database
div = {
'user1': {'password': '123'},
'user2': {'password': '123'},
'user3': {'password': '123'},
}
goods = [
{"name": "电脑", "price": 1999},
{"name": "鼠标", "price": 10},
{"name": "游艇", "price": 20},
{"name": "美女", "price": 998},
]
# 读取用户购买信息 save_cart->exist [username as keys]
save_cart = {}
if os.path.exists(FILE_PATH):
with open(FILE_PATH, mode="r", encoding='utf-8') as f:
for line in f.readlines():
save_cart.update(eval(line.strip()))
# login loop name->exist
while True:
name = input("登录用户名:").strip()
if name == 'q':
exit('Bye.')
if name not in div:
print("用户名错误")
if name in div:
password = input("请输入密码:").strip()
if password == div[name]['password']:
print("欢迎回来,%s!" % name)
break
else:
print("密码错误")
# money->exist lst->exist
a = save_cart.get(name)
if a is not None:
money = a.get('m')
lst = a.get('ls')
print('-------已购买-------')
print('您的余额为¥', money)
for index, p in enumerate(lst):
print('%s. %s %s' % (index, p[0], p[1]))
else:
money = int(input('Please input your salary:'))
lst = []
#shopping loop
while True:
print("--------商品列表---------")
for index, p in enumerate(goods):
print("%s. %s %s" % (index, p.get('name'), p.get('price')))
choice = input("输入想买的商品编号:")
if choice.isdigit():
choice = int(choice)
if choice >= 0 and choice < len(goods):
if money > goods[choice].get('price'):
money -= goods[choice].get('price')
lst.append([goods[choice]['name'], goods[choice]['price']])
print("Added product \033[31;1m%s,¥%s\033[0m into shopping cart." % (
goods[choice].get('name'), goods[choice].get('price')))
else:
print("余额不足。")
else:
print("商品不存在")
elif choice == 'q':
if len(lst) > 0:
print("-------你已购买以下商品-------")
for index, p in enumerate(lst):
print("%s. %s ¥%s" % (index, p[0], p[1]))
print("你的余额为:\033[31;1m%s\033[0m" % money)
break
elif choice == 'd':
if len(lst) > 0:
print("-------你已购买以下商品-------")
for index, p in enumerate(lst):
print("%s. %s ¥%s" % (index, p[0], p[1]))
print("你的余额为:\033[31;1m%s\033[0m" % money)
# save 2 file
with open(FILE_PATH, mode='w', encoding='utf-8') as f:
save_cart.update({name: {'m': money, 'ls': lst}})
# {'user1': {'m': 0, 'ls': []}}
f.write(str(save_cart))