Python學習之路 002
阿新 • • 發佈:2017-05-21
else 內容 readline input rjust price info class 信息
今天寫著購物車的作業,最頭疼的是文件操作了
尤其是文件的打開模式 w r a 最TM的頭疼
r+模式可讀可寫,但是寫的內容會根據文件指針去覆蓋之前的內容,當文件需要修改時,強烈建議不要用這種模式,會有一個坑
下面說說文件的思路吧,還沒有學習函數,因此代碼起來很亂
1.設置接口
#user接口
if ident_flag == ‘u‘:
首先讀入文件的數據
# 商品信息 with open("goods.txt",‘r‘) as goods_file: goods_info = {} forline in goods_file.readlines(): item = line.strip(‘\n‘).split(‘ ‘) goods_info[item[0]] = item[1] # 余額信息 with open("balance.txt",‘r‘) as balance_file: balance = int( balance_file.readline().strip(‘\n‘) )
購買商品
# 購買商品 buy_name = input("Which goods would your like to buy?(input the name of goods)>>: ") if buy_name in goods_info: if balance > int( goods_info[buy_name] ): balance = balance - int( goods_info[buy_name] ) shopping_list[buy_name] = goods_info[buy_name]else: print("I‘m sorry to hear that you have not enough money to buy this") else: print("Sorry sir, there is not the goods that you need!!\n")
結賬
# 結算 with open("balance.txt",‘w‘) as goods_file: goods_file.write(str(balance))
#manager接口
elif ident_flag == ‘m‘:
首先讀入文件
# 商品信息 with open("goods.txt",‘r‘) as goods_file: goods_info = {} for line in goods_file.readlines(): item = line.strip(‘\n‘).split(‘ ‘) goods_info[item[0]] = item[1]
增加商品
# 增加商品 if choice == ‘a‘: print("you are adding a goods".center(50,‘-‘)) goods_name = input("The goods_name is: ") goods_price = input("The goods_price is: ") print("\n".rjust(51,‘-‘)) info = goods_name + ‘ ‘ + goods_price + ‘\n‘ with open("goods.txt", ‘a‘) as goods_file: goods_file.write(info)
修改商品
# 修改商品 elif choice == ‘m‘: print("You are modify a goods".center(50, ‘-‘)) goods_name = input("The goods_name is: ") if goods_name in goods_info: goods_price = input("The goods_price is: ") goods_info[goods_name] = goods_price with open("goods.txt", ‘w+‘) as goods_file: for item in goods_info: info = item + ‘ ‘ + goods_info[item] + ‘\n‘ goods_file.write(info) else: print("Sorry sir, there is not -{_goods_name}-!".format(_goods_name = goods_name))
刪除商品
# 刪除商品 elif choice == ‘d‘: print("you are delete a goods".center(50, ‘-‘)) goods_name = input("The goods_name is: ") if goods_name in goods_info: goods_info.pop(goods_name) with open("goods.txt",‘w‘): for item in goods_info: info = item + ‘ ‘ + goods_info[item] + ‘\n‘ goods_file.write(info)
Python學習之路 002