Python文件处理之购物车系统
一、Python文件处理之购物车系统
- 用户名和密码存放于文件中,格式为:nick,nick123
- 加载所有用户名,检查用户名是否已存在
- 启动程序后,先登录,登录成功则让用户输入工资,然后打印商品列表,失败则重新登录,超过三次则退出程序
- 允许用户根据商品编号购买商品
- 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
- 可随时退出,退出时,打印已购买商品和余额
import os
product_list = [
['iphone17', 998],
['Python教程', 9.9],
['su7', 2000],
['byd', 999],
['coke', 1.8],
['锅巴', 20]
]
shopping_cart = {} # 存储用户购物车信息的字典
current_userinfo = [] # 存储当前登录用户的信息
# 原始字符串,避免被转义
db_file = r'D:\db.txt' # 用户数据文件路径
while True:
print('登录\n注册\n购物')
choice = input('>>:').strip()
if choice == '1':
flag = True
count = 0
while flag:
if count == 3:
print('尝试次数过去,退出程序。。。')
break
uname = input('用户名:').strip()
password = input('密码:').strip()
with open(db_file, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
user_info = line.split(',')
uname_db = user_info[0]
pwd_db = user_info[1]
balance_db = int(user_info[2])
if uname == uname_db and password == pwd_db:
print('登录成功!')
current_userinfo = [uname_db, balance_db]
print('用户信息:', current_userinfo)
flag = False
break
else:
print('检查用户名或密码错误!')
count += 1
elif choice == '2':
# 步骤1:预先加载所有用户名
existing_users = set()
try:
with open(db_file, 'r', encoding='utf-8') as f:
for line in f:
parts = line.strip().split(',')
if parts: # 确保非空行
existing_users.add(parts[0])
except FileNotFoundError:
# 文件不存在时创建空集合
existing_users = set()
# 步骤2:用户名输入与验证循环
while True:
uname = input('请输入用户名:').strip()
# 检查用户名是否已存在
if uname in existing_users:
print(f"用户名 '{uname}' 已被占用,请选择其他用户名")
else:
break # 唯一用户名,退出循环
while True:
password1 = input('情输入密码:').strip()
password2 = input('情确认密码:').strip()
if password1 == password2:
break
else:
print('两次输入密码不一致,请再次输入!!')
balance = input('请输入充值金额:').strip()
with open(db_file, 'a', encoding='utf-8') as f:
f.write('%s,%s,%s\n' % (uname, password1, balance))
elif choice == '3':
# 登录成功,开始购物
uname_db = current_userinfo[0]
balance_db = current_userinfo[1]
print(f'尊敬的用户{uname_db},您的账户余额为{balance_db}')
flag = True
while flag:
for index, product in enumerate(product_list):
print(index, product)
choice = input('输入商品的编号购物,输入‘q’退出>>:').strip()
if choice.isdigit():
choice = int(choice)
if choice < 0 or choice >= len(product_list):
continue
pname = product_list[choice][0]
pprice = product_list[choice][1]
if balance_db > pprice:
if pname in shopping_cart:
shopping_cart[pname]['count'] += 1
else:
shopping_cart[pname] = {
'pprice': pprice,
'count': 1
}
balance_db -= pprice
current_userinfo[1] = balance_db
print(
"Added product " + pname +
" into shopping cart,your current balance "
+ str(balance_db))
else:
print(f'你太穷了!商品价格是{pprice},你还差{pprice - balance_db}')
print(shopping_cart)
elif choice == 'q':
print("""
---------------------------------已购买商品列表---------------------------------
id 商品 数量 单价 总价
""")
total_cost = 0
for i, key in enumerate(shopping_cart):
print('%22s%18s%18s%18s%18s' %
(i, key, shopping_cart[key]['count'],
shopping_cart[key]['pprice'],
shopping_cart[key]['pprice'] *
shopping_cart[key]['count']))
total_cost += shopping_cart[key]['pprice'] * shopping_cart[key]['count']
print("""
您的总花费为: %s
您的余额为: %s
---------------------------------end---------------------------------
""" % (total_cost, balance_db))
while flag:
inp = input("确认购买(yes/no?)>>:").strip()
if inp not in ['Y', 'N', 'y', 'n', 'yes', 'no']:
continue
if inp in ['Y', 'y', 'yes']:
# 将余额写入文件
src_file = db_file
dst_file = r'%s.swap' % db_file
with open(src_file, 'r', encoding='utf-8') as read_f, \
open(dst_file, 'w', encoding='utf-8') as write_f:
for line in read_f:
if line.startswith(uname_db): # 字符串前缀匹配
l = line.strip('\n').split(',') # 移除行尾换行符,按逗号分割字符串
l[-1] = str(balance_db)
line = ','.join(l) + '\n'
write_f.write(line)
os.remove(src_file)
os.rename(dst_file, src_file)
print('购买成功,耐心等待发货。')
# 重置购物车,清除用户会话,退出购物循环
shopping_cart = {}
current_userinfo = []
flag = False
else:
print("输入形式非法")
elif choice == 'q':
break
else:
print('非法操作')

浙公网安备 33010602011771号