lock_file = open('C:\\aaaaaaaaaaaaa\\custom.txt','r+')
lock = lock_file.read().split("\n")
print(lock)
usrname = input("请输入您的名字:")
not_new_custom = list(filter(lambda x: usrname in x, lock))
#print(not_new_custom)
if not not_new_custom:
salary = int(input("您是第一次访问,请输入你的salary:"))
print("您现在的余额是:",salary)
else:
print(usrname,",您好,欢迎回来")
salary = not_new_custom[0]
salary = salary.split(":")
salary = int(salary[1])
print("您现在的余额是:", salary)
lock_file_Commodity_shelves = open('C:\\aaaaaaaaaaaaa\\Commodity_shelves .txt','r+')
Commodity_shelves = lock_file_Commodity_shelves.read().split("\n")
print(Commodity_shelves)
shopping_car = []
buy_flag = 1
j = 0
while buy_flag:
for i in Commodity_shelves:
print(j,i)
j +=1
buy = input("请输入你要购买的商品编号,按q退出购物:")
if buy == 'q':
buy_flag = 0
#break
else:
buy = int(buy)
price = Commodity_shelves[buy]
price = price.split(",")
price = int(price[1])
if salary > price:
shopping_car.append(Commodity_shelves[buy])
salary -= price
print("你现在的余额是:",salary)
print("你现在已经购买的东西有:",shopping_car)
else:
print("余额不足,现在的余额为:",salary,"按q退出购物")
j = 0
if not not_new_custom:
lock_file.write(usrname + ":" + str(salary) + "\n")
lock_file.close()
先把文件读出来,存在列表里,然后在每一个元素去判断是否包含指定的字符串,如果包含则不覆盖写入,跳过,不包含则覆盖写入文件
else:
lock_file.close()
with open("C:\\aaaaaaaaaaaaa\\custom.txt", "r", encoding="utf-8") as f:
lines = f.readlines()
# print(lines)
with open("C:\\aaaaaaaaaaaaa\\custom.txt", "w", encoding="utf-8") as f_w:
for line in lines:
if usrname in line:
continue
f_w.write(line)
f_w.write(usrname + ":" + str(salary) + "\n")

浙公网安备 33010602011771号