>>>判断用户工资是否有记录
>>>能够从文件中读取商品列表
>>>能够选择想要的商品,并扣除工资
>>>打印并保存订单信息以及工资余额
>>>能够读取商品列表
>>>能够修改商品价格并保存
>>>能够添加商品并保存
>>>能够删除商品并保存
‘‘‘实现购物城功能---文件操作版‘‘‘
# 接口 cart_user 和 cart_merchant
role = input(‘请输入你要进入的角色接口(user/merchant)‘)
if role == ‘user‘:
from day2 import cart_user
elif role == ‘merchant‘:
from day2 import cart_merchant
else:
print("你输入的角色接口有误!")
‘‘‘实现购物车功能 --- 用户接口‘‘‘
# 获得商品列表
def get_product():
product_list = []
with open(‘product.txt‘, ‘r‘) as f:
for i in f.readlines():
i = i.replace(‘\n‘, ‘‘)
product_list.append(i.split(‘:‘))
return product_list
# 保存商品列单及余额
def save_product(goods_order_salary):
with open(‘shopping.txt‘, ‘a‘) as f:
f.write(goods_order_salary + ‘\n‘)
# 读取工资
def read_salary():
with open(‘shopping.txt‘, ‘r‘) as f:
data = f.read()
return data
# 判断 salary 是否有记录
data = read_salary()
if ‘balance‘ in data:
salary = data.split(‘:‘)[-1]
print(‘您目前的余额为:‘+salary)
else:
salary = input("请输入你的工资:")
# 主程序
shopping_list = []
# if salary.isdigit():
salary = int(salary)
while True:
product_list = get_product()
for index, item in enumerate(product_list):
print(index, item)
user_choice = input(‘选择你想要的产品:‘)
if user_choice.isdigit():
user_choice = int(user_choice)
if user_choice < len(product_list) and user_choice >= 0:
p_item = product_list[user_choice]
p_item[1] = int(p_item[1])
if p_item[1] <= salary:
shopping_list.append(p_item)
salary -= p_item[1]
print(‘Added %s into shopping cart.your present balance is \033[31;1m%s\033[0m‘ % (p_item, salary))
save_product(str(p_item))
else:
print(‘\033[41;1m你的余额只剩[%s]啦,还买个毛线\033[0m‘ % salary)
else:
print(‘product code [%s] is not exist!‘ % user_choice)
elif user_choice == ‘q‘:
print(‘--------shopping list-----------‘)
for p in shopping_list:
print(p)
print(‘Your current balance:‘, salary)
save_product(‘\nyour present balance is :‘ + str(salary) + ‘\n‘)
exit()
else:
print(‘invalid option‘)
‘‘‘实现购物车功能 --- 商家接口‘‘‘
# 获得商品列表
def get_product():
product_list = []
with open(‘product.txt‘, ‘r‘) as f:
for i in f.readlines():
i = i.replace(‘\n‘, ‘‘)
product_list.append(i.split(‘:‘))
return product_list
# 保存商品
def save_product(product_list):
with open(‘product.txt‘,‘w‘) as f:
for i in product_list:
i = str(i).replace(‘[‘, ‘‘)
i = str(i).replace(‘]‘, ‘‘)
i = str(i).replace(‘ ‘, ‘‘)
f.write(i+‘\n‘)
product_list = get_product()
while True:
for index,item in enumerate(product_list):
print(index,item)
choice = input(‘请输入要修改的商品序号||按a添加||按q退出:‘)
if choice.isdigit():
choice = int(choice)
p_item = product_list[choice]
print(p_item)
price = input("请输入修改后的价格:")
product_list[choice][1] = price
print(product_list)
save_product(product_list)
print("修改成功!")
elif choice == ‘a‘:
name = input(‘请输入你要添加的商品名称:‘)
price = input(‘请输入你要添加的商品价格:‘)
add_pro = [name,price]
product_list.append(add_pro)
print(product_list)
save_product(product_list)
print(‘添加成功!‘)
elif choice == ‘q‘:
exit()
else:
print("输入无效!")
原文:https://www.cnblogs.com/petrolero/p/8992411.html