首页 / PYTHON / Python学习之路 002
Python学习之路 002
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python学习之路 002,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2268字,纯文字阅读大概需要4分钟。
内容图文
![Python学习之路 002](/upload/InfoBanner/zyjiaocheng/1120/3a752a75a0fe41248d4773277bc439cf.jpg)
今天写着购物车的作业,最头疼的是文件操作了
尤其是文件的打开模式 w r a 最TM的头疼
r+模式可读可写,但是写的内容会根据文件指针去覆盖之前的内容,当文件需要修改时,强烈建议不要用这种模式,会有一个坑
下面说说文件的思路吧,还没有学习函数,因此代码起来很乱
1.设置接口
#user接口
if ident_flag == ‘u‘:
首先读入文件的数据
# 商品信息 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] # 余额信息 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)
原文:http://www.cnblogs.com/JackyPeng/p/6883666.html
内容总结
以上是互联网集市为您收集整理的Python学习之路 002全部内容,希望文章能够帮你解决Python学习之路 002所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。