Python基础,day2
程序练习
程序:购物车程序
需求:
- 启动程序后,让用户输入工资,然后打印商品列表
- 允许用户根据商品编号购买商品
- 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
- 可随时退出,退出时,打印已购买商品和余额
menu = [['Iphone',4288],['Mac pro',1200],['Book',80]] buy_menu = [] salay = input("Pls input your salay:") if salay.isdigit(): salay = int(salay) while True: for index,item in enumerate(menu): #print(menu.index(item),item) print(index,item) user_choice = input("Pls input your choose:") if user_choice.isdigit(): user_choice = int(user_choice) if user_choice < len(menu) and user_choice >= 0: p_list = menu[user_choice] if p_list[1] <= salay: buy_menu.append(p_list) print("Added %s to the shopping list" % (p_list)) salay -= p_list[1] print("The balance is %s" % (salay)) else: print("Your money is no enough,the balance is %s" % (salay)) print("Your shopping list is",buy_menu) exit() else: print("Sorry,the number of %s is not in the meun list." % (user_choice)) else: print("Pls input the correct number:") status = input("Do you want choose another[c/q]:") if status == "q": print("Your list of buy is", buy_menu) print("Your balance is", salay) exit(0) else: print("Pls input the number of your salay.")
程序: 三级菜单
要求:
- 打印省、市、县三级菜单
- 可返回上一级
- 可随时退出程序
menu = { "jiangxi": { "nanchang": { "xinjianxian": ["ncu", "bank"], "nanchangxian": ["caijingdaxue", "jishuxueyuan"] }, "jiujiang": { "xiushuixian": "修水县地图", "jiujiangxian": "九江县地图" } }, "guangdong": { "shenzhen": { "longhuaqu": "龙华区地图", "luohuqu": "罗湖区地图" } } } menu["jiangxi"]["nanchang"]["xinjianxian"][0] += " univercity" exit_flag = False while not exit_flag: for i in menu: print(i) choice = input("1>>:") if choice in menu: while not exit_flag: for i2 in menu[choice]: print("\t", i2) choice2 = input("2>>:") if choice2 in menu[choice]: while not exit_flag: for i3 in menu[choice][choice2]: print("\t\t", i3) choice3 = input("3>>:") if choice3 in menu[choice][choice2]: for i4 in menu[choice][choice2][choice3]: print("\t\t\t",i4) choice4 = input("4按b返回上层>>:") if choice4 == "b": pass elif choice4 == "q": exit_flag = True if choice3 == "b": break elif choice3 == "q": exit_flag = True if choice2 == "b": break elif choice2 == "q": exit_flag = True
5. 文件操作
对文件操作流程
- 打开文件,得到文件句柄并赋值给一个变量
- 通过句柄对文件进行操作
- 关闭文件
风吹雨成花
时间追不上白马
你年少掌心的梦话
依然紧握着吗
云翻涌成夏
眼泪被岁月蒸发
这条路上的你我她
有谁迷路了吗
我们说好不分离
要一直一直在一起
就算与时间为敌
就算与全世界背离
风吹亮雪花
吹白我们的头发
当初说一起闯天下
你们还记得吗
那一年盛夏
心愿许的无限大
我们手拉手也成舟
划过悲伤河流
你曾说过不分离
要一直一直在一起
现在我想问问你
是否只是童言无忌
天真岁月不忍欺
青春荒唐我不负你
大雪求你别抹去
我们在一起的痕迹
大雪也无法抹去
我们给彼此的印记
今夕何夕
青草离离
明月夜送君千里
等来年 秋风起
#文件句柄 f = open("music.py","r",encoding="utf-8") #读取文件内容,不可写 print(f.read()) #读取所有 print(f.readlines()) #读取所有行,输出成列表 print(f.readline()) #读取一行 #low methon ''' for index,line in enumerate(f.readlines()): if index == 4: print("line pass".center(50,"-")) continue print(line.strip()) #strip()取消空格和\n换行 ''' #higher methon ''' count = 0 for line in f: #一行一行读取,内存内只保留一行,迭代器 if count == 4: print("line pass".center(50, "-")) count += 1 continue print(line.strip()) count += 1 ''' #f = open("music.py","w",encoding="utf-8") #文件存在会覆盖写入,不存在会新建写入,不可读 #f.write("test write") #f = open("music.py","a",encoding="utf-8") #追加不会覆盖原有,但不可读 #f.write("\ntest append\n") #print(f.read(5)) #读取几个字 #print(f.tell()) #把文件句柄所在的指针指向的位置打印出来,按字符计数 #f.seek(0) #移动光标,回到某个位置 ##print(f.seekable()) #是否可以光标移动 #print(f.read(5)) #print(f.encoding) #打印文件编码 #print(f.name) #打印文件名 #print(f.isatty()) #是否是终端设备,例如:打印机 #f.flush() #把文件从内存刷新到磁盘中 #f.close() #关闭文件 #print(f.closed) #判断文件是否关闭 #f.truncate(10) #截断,从头开始截取 #f = open("music.py","r+",encoding="utf-8") #文件句柄,读写,当指针指向为0的时候,替换写在最前面,当指针指向非零的时候,以追加的模式最加到最后 #f = open("music.py","w+",encoding="utf-8") #文件句柄,写读,很少用 #f = open("music.py","a+",encoding="utf-8") #文件句柄,追加读写,文件打开指针就跳到结尾,读需要把指针移动到前面位置 #f = open("music.py","rb") #文件句柄,二进制文件 #f = open("music.py","wb") f = open("music.py","ab") f.write("hello world\n".encode())
文件修改
f = open("music.py","r",encoding="utf-8") f_new = open("music_new.py","w",encoding="utf-8") for line in f: if "我们说好" in line: line = line.replace("我们说好","我们一起说好") f_new.write(line) f.close() f_new.close()
打开文件的模式有:
- r,只读模式(默认)。
- w,只写模式。【不可读;不存在则创建;存在则删除内容;】
- a,追加模式。【可读; 不存在则创建;存在则只追加内容;】
"+" 表示可以同时读写某个文件
- r+,可读写文件。【可读;可写;可追加】
- w+,写读
- a+,同a
"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)
- rU
- r+U
"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)
- rb
- wb
- ab
with语句
为了避免打开文件后忘记关闭,可以通过管理上下文,当with代码块执行完毕时,内部会自动关闭并释放文件资源。
在Python 2.7 后,with又支持同时对多个文件的上下文进行管理。
import sys find_str = sys.argv[1] replace_str = sys.argv[2] #with 语句 with open("music.py","r",encoding="utf-8") as f, \ open("music_new.py", "w", encoding="utf-8") as f_new: for line in f: if find_str in line: line = line.replace(find_str, replace_str) f_new.write(line)
6. 字符编码与转码
说明:
1.在python2默认编码是ASCII, python3里默认是unicode
2.unicode 分为 utf-32(占4个字节),utf-16(占两个字节),utf-8(占1-4个字节), so utf-16就是现在最常用的unicode版本, 不过在文件里存的还是utf-8,因为utf8省空间
3.在py3中encode,在转码的同时还会把string 变成bytes类型,decode在解码的同时还会把bytes变回string
#-*- coding:utf-8 -*- #声明文件编码格式 import sys print(sys.getdefaultencoding()) #python3 默认编码格式是utf-8 s = "你好" #unicode格式,Python3里所有的数据类型都是unicode s_to_gbk = s.encode("gbk") print(s_to_gbk) s_to_utf8 = s.encode() print(s_to_utf8) gbk_to_utf8 = s_to_gbk.decode("gbk").encode("utf-8") print(gbk_to_utf8) print("分割线".center(50,"-")) print(s.encode("utf-8")) print(s.encode("gbk")) print(s.encode("gb2312")) print(s.encode("gb2312").decode("gb2312").encode("utf-8").decode("utf-8").encode("gbk"))
程序练习
程序1: 实现简单的shell sed替换功能
sed_before = input("Pls input the old word that you want sed:") sed_after = input("Pls input the new word that you want sed:") count = 0 f = open("music.py","r",encoding="utf -8") f_sed = open("music_sed.py","w",encoding="utf-8") for line in f: if sed_before in line: line = line.replace(sed_before,sed_after) count += 1 f_sed.write(line) if count == 0: print("The old word is not in the file,pls config") f.close() f_sed.close()
sed_before = input("Pls input the old word that you want sed:") sed_after = input("Pls input the new word that you want sed:") count = 0 with open("music.py","r",encoding="utf -8") as f,\ open("music_sed.py","w",encoding="utf-8") as f_sed: for line in f: if sed_before in line: line = line.replace(sed_before, sed_after) count += 1 f_sed.write(line) if count == 0: print("The old word is not in the file,pls config")
程序2:修改haproxy配置文件