首页 > 代码库 > Python-w2
Python-w2
一个购物车实例,大量的列表,字典,文件互相写入,读取操作。
对于嵌套字典的取值,比较繁琐。
该程序功能较为单一,代码了较大,没有使用函数,有很多地方可以改进。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os,sys,time
# init menu prod list
_prod_list = []
# init a shopping cart
_shopping_his = []
_shopping_cart = []
# init user info list
_user = {}
# load prod list
if not os.path.exists("w2_prod.txt"):
open("w2_prod.txt", "w").close()
else:
with open("w2_prod.txt","r") as prod_list:
lines = prod_list.readlines()
if lines:
print("Load prod list...")
for line in lines:
_prod_list.append(line.strip())
else:
print("Nothing in prod list. Please import production with the format: prod_name,prod_price")
exit()
# create user list and buy list
if not os.path.exists("w2_user.txt"):
open("w2_user.txt","w").close()
if not os.path.exists("w2_buy.txt"):
open("w2_buy.txt","w").close()
# init user info
with open("w2_user.txt","r+") as names:
lines = names.readlines()
if lines:
print("Load user information...")
for i in range(len(lines)):
_user[str(i)] = {}
(_id,_uname,_upwd,_ustate,_ubalance) = lines[i].strip().split(",",5)
_user[str(i)]["name"] = _uname
_user[str(i)]["password"] = _upwd
_user[str(i)]["state"] = _ustate
_user[str(i)]["balance"] = int(_ubalance)
else:
print("It is empty")
print("Hello, it is your first time to access....")
print("Please enter your information:")
_name = input("Name:")
_pwd = input("Password:")
_state = ‘enable‘
_salary = int(input("Salary:"))
_uid = str(len(_user))
names.write("%s,%s,%s,%s,%d" %(_uid,_name,_pwd,_state,_salary))
#load user info
_user[_uid] = {}
_user[_uid]["name"] = _name
_user[_uid]["password"] = _pwd
_user[_uid]["state"] = _state
_user[_uid]["balance"] = _salary
#login system and user identity authentication
print("Login".center(30,"="))
_name = input("Name:")
with open("w2_user.txt", "r") as users:
lines = users.readlines()
for i in range(len(lines)):
if _name == _user[str(i)]["name"]:
_pwd = input("password:")
if _pwd == _user[str(i)]["password"]:
print("Welcome to login !")
else:
print("The password is error...")
exit()
else:
print("The user is not exist.")
exit()
#load shopping cart
with open("w2_buy.txt","r") as buy_lists:
lines = buy_lists.readlines()
if lines:
print("\033[1;37;44m Shopping_History \033[0m ".center(30,"="))
for i in lines:
_shopping_his.append(i.strip())
print("\033[1;37;44m",_shopping_his,"\033[0m")
else:
print("Nothing in shopping cart".center(40,"="))
#load balance
_balance = []
for i in _user.keys():
balance = int(_user[i]["balance"])
_balance.append(balance)
print("\033[1;31m Balance:",_balance,"\033[0m")
balance = int(_balance[0])
while True:
# load prod list
print("The Production List".center(30,"="))
for index, menu_list in enumerate(_prod_list):
print(index, menu_list)
#user operation
_select1 = input("Your selection[History:h|Recharge:r|Quit:q]:")
if _select1.isdigit():
_select1 = int(_select1)
if _select1 > -1 and _select1 <= len(_prod_list):
(pname,pprice) = str(_prod_list[_select1]).strip().split(",")
pprice = int(pprice)
for i in _user.keys():
balance = _user[str(i)]["balance"]
print(balance)
print(pprice)
if balance >= pprice:
balance -= pprice
print("\033[1;34m Add %s to shopping cart. \033[0m" %pname)
_shopping_cart.append(pname)
print("\033[1;35m Shopping_Cart:",_shopping_cart,"\033[0m")
print("Shopping His:",_shopping_his)
print("\033[1;31m Balance RMB:",balance,"\033[0m")
for i in _user.keys():
_user[i]["balance"] = balance
else:
print("\033[1;31m Balance is not enough.\033[0m")
continue
else:
print("\033[1;31m It is out of range! \033[0m")
elif _select1 == "q":
print("\033[1;35m Total:", _shopping_cart, "\033[0m")
print("Saving summary report of \033[1;31m w2_report.txt \033[0m ...")
for i in range(20):
sys.stdout.write("#")
sys.stdout.flush()
time.sleep(0.2)
#build report
shopping = _shopping_cart+_shopping_his
item = set(shopping)
with open("w2_report.txt","w") as report:
for i in item:
print(i,shopping.count(i),file=report)
#update user info
for i in _user.keys():
_quid = i
_qname = _user[str(i)]["name"]
_qpassword = _user[str(i)]["password"]
_qstate = _user[str(i)]["state"]
_qbalance = _user[str(i)]["balance"]
with open("w2_user.txt","w+") as names:
names.write("%s,%s,%s,%s,%d" %(_quid,_qname,_qpassword,_qstate,_qbalance) )
#store prod in file
with open("w2_buy.txt","a") as saves:
for i in _shopping_cart:
print(i,file=saves)
exit()
elif _select1 == "h":
print("\033[1;37;44m You had got items before:",_shopping_his,"\033[0m")
elif _select1 == "r":
_money = input("How much cash do you want to add:")
if _money.isdigit():
_money = int(_money)
for i in _user.keys():
_user[str(i)]["balance"] = int(_user[str(i)]["balance"]) + _money
print(_user[str(i)]["balance"])
break
else:
print("\033[1;31m It is not a digit! \033[0m")
continue
else:
print("\033[1;31m It is not a digit! \033[0m")
本文出自 “Clark的运维” 博客,谢绝转载!
Python-w2