一、文件處理實戰之購物車系統
-
用戶名和密碼存放於文件中,格式為:nick|nick123
-
啟動程序后,先登錄,登錄成功則讓用戶輸入工資,然后打印商品列表,失敗則重新登錄,超過三次則退出程序
-
允許用戶根據商品編號購買商品
-
用戶選擇商品后,檢測余額是否夠,夠就直接扣款,不夠就提醒
-
可隨時退出,退出時,打印已購買商品和余額
import os
product_list = [
['Iphone7', 5800],
['Coffee', 30],
['疙瘩湯', 10],
['Python Book', 99],
['Bike', 199],
['ViVo X9', 2499],
]
shopping_cart = {}
current_userinfo = []
db_file = r'db.txt'
while True:
print('''
登陸
注冊
購物
''')
choice = input('>>: ').strip()
if choice == '1':
#1、登陸
tag = True
count = 0
while tag:
if count == 3:
print('嘗試次數過多,退出。。。')
break
uname = input('用戶名:').strip()
pwd = input('密碼:').strip()
with open(db_file, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip('\n')
user_info = line.split(',')
uname_of_db = user_info[0]
pwd_of_db = user_info[1]
balance_of_db = int(user_info[2])
if uname == uname_of_db and pwd == pwd_of_db:
print('登陸成功')
# 登陸成功則將用戶名和余額添加到列表
current_userinfo = [uname_of_db, balance_of_db]
print('用戶信息為:', current_userinfo)
tag = False
break
else:
print('用戶名或密碼錯誤')
count += 1
elif choice == '2':
uname = input('請輸入用戶名:').strip()
while True:
pwd1 = input('請輸入密碼:').strip()
pwd2 = input('再次確認密碼:').strip()
if pwd2 == pwd1:
break
else:
print('兩次輸入密碼不一致,請重新輸入!!!')
balance = input('請輸入充值金額:').strip()
with open(db_file, 'a', encoding='utf-8') as f:
f.write('%s,%s,%s\n' % (uname, pwd1, balance))
elif choice == '3':
if len(current_userinfo) == 0:
print('請先登陸...')
else:
#登陸成功后,開始購物
uname_of_db = current_userinfo[0]
balance_of_db = current_userinfo[1]
print('尊敬的用戶[%s] 您的余額為[%s],祝您購物愉快' % (uname_of_db, balance_of_db))
tag = True
while tag:
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_of_db > pprice:
if pname in shopping_cart: # 原來已經購買過
shopping_cart[pname]['count'] += 1
else:
shopping_cart[pname] = {
'pprice': pprice,
'count': 1
}
balance_of_db -= pprice # 扣錢
current_userinfo[1] = balance_of_db # 更新用戶余額
print(
"Added product " + pname +
" into shopping cart,[42;1myour current balance "
+ str(balance_of_db))
else:
print("買不起,窮逼! 產品價格是{price},你還差{lack_price}".format(
price=pprice, lack_price=(pprice - balance_of_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_of_db))
while tag:
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_of_db):
l = line.strip('\n').split(',')
l[-1] = str(balance_of_db)
line = ','.join(l) + '\n'
write_f.write(line)
os.remove(src_file)
os.rename(dst_file, src_file)
print('購買成功,請耐心等待發貨')
shopping_cart = {}
current_userinfo = []
tag = False
else:
print('輸入非法')
elif choice == 'q':
break
else:
print('非法操作')
登陸
注冊
購物
>>: 2
請輸入用戶名:nick
請輸入密碼:123
再次確認密碼:123
請輸入充值金額:10000
登陸
注冊
購物
>>: 1
用戶名:nick
密碼:123
登陸成功
用戶信息為: ['nick', 10000]
登陸
注冊
購物
>>: 3
尊敬的用戶[nick] 您的余額為[10000],祝您購物愉快
0 ['Iphone7', 5800]
1 ['Coffee', 30]
2 ['疙瘩湯', 10]
3 ['Python Book', 99]
4 ['Bike', 199]
5 ['ViVo X9', 2499]
輸入商品編號購物,輸入q退出>>: 0
Added product Iphone7 into shopping cart,[42;1myour current balance 4200
{'Iphone7': {'pprice': 5800, 'count': 1}}
0 ['Iphone7', 5800]
1 ['Coffee', 30]
2 ['疙瘩湯', 10]
3 ['Python Book', 99]
4 ['Bike', 199]
5 ['ViVo X9', 2499]
輸入商品編號購物,輸入q退出>>: 1
Added product Coffee into shopping cart,[42;1myour current balance 4170
{'Iphone7': {'pprice': 5800, 'count': 1}, 'Coffee': {'pprice': 30, 'count': 1}}
0 ['Iphone7', 5800]
1 ['Coffee', 30]
2 ['疙瘩湯', 10]
3 ['Python Book', 99]
4 ['Bike', 199]
5 ['ViVo X9', 2499]
輸入商品編號購物,輸入q退出>>: q
---------------------------------已購買商品列表---------------------------------
id 商品 數量 單價 總價
0 Iphone7 1 5800 5800
1 Coffee 1 30 30
您的總花費為: 5830
您的余額為: 4170
---------------------------------end---------------------------------
確認購買(yes/no?)>>: yes
購買成功,請耐心等待發貨
登陸
注冊
購物
>>: q