f = open('chenli.txt') #打开文件
first_line = f.readline()
print('first line:',first_line) #读一行
print('我是分隔线'.center(50,'-'))
data = f.read() # 读取剩下的所有内容,文件大时不要用
print(data) #打印读取内容f.close() #关闭文件
1 文件句柄 = open('文件路径', '模式')
打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。
打开文件的模式有:
- r ,只读模式【默认模式,文件必须存在,不存在则抛出异常】
- w,只写模式【不可读;不存在则创建;存在则清空内容】
- x, 只写模式【不可读;不存在则创建,存在则报错】
- a, 追加模式【可读; 不存在则创建;存在则只追加内容】
"+" 表示可以同时读写某个文件
- r+, 读写【可读,可写】
- w+,写读【可读,可写】
- x+ ,写读【可读,可写】
- a+, 写读【可读,可写】
"b"表示以字节的方式操作
- rb 或 r+b
- wb 或 w+b
- xb 或 w+b
- ab 或 a+b
注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型,不能指定编码
、写程序
a. 文件操作时 with 的作用?
b. 写程序:利用 with 实现同时打开两个文件(一读,一写,并将读取的内容写入到写入模式的文件中)
with open("test","r",encoding="utf8") as a,open("test1","w",encoding="utf8") as b:a1 = a.read()b.write(a1)
# 字符串----encode----》bytes
# bytes-----decode---》字符串
f1 = open("test","wb") # b的方式不能指定编码
f1.write("你好1".encode("utf8"))
f1.close()f2 = open("test","ab") # b的方式不能指定编码
f2.write("你好2".encode("utf8"))
f2.close()f = open("test","rb") # b的方式不能指定编码
data = f.read()
print(data.decode("utf8"))
f.close()
fo = open("test","r+",encoding="utf8")
print(fo.closed) #如果文件关闭返回True
print(fo.encoding) #查看使用open打开文件的编码
fo.flush() #将文件从内存刷到硬盘上
print(fo.tell()) #查看光标的位置,以字节为单位
fo.seek(15) #移动光标的位置,以字节为单位
print(fo.tell())
fo.truncate(11) #保留文件字节的内容,文件要是可写的方式打开,但w 和 w+ 的方式除外
fo = open("test","r+",encoding="utf8")
fo.seek(15,0) #第二个参数,0代表光标从头开始算,1代表光标从上一次开始算,2代表光标从最后开始算
fo.seek(15.1)
fo.seek(15.2)
练习:
haproxy.conf 文件
globallog 127.0.0.1 local2daemonmaxconn 256log 127.0.0.1 local2 info
defaultslog globalmode httptimeout connect 5000mstimeout client 50000mstimeout server 50000msoption dontlognulllisten stats :8888stats enablestats uri /adminstats auth admin:1234frontend oldboy.orgbind 0.0.0.0:80option httplogoption httpcloseoption forwardforlog globalacl www hdr_reg(host) -i www.oldboy.orguse_backend www.oldboy.org if wwwbackend www.oldboy1.orgserver 1.1.1.1 1.1.1.1 weight 999 maxconn 333server 11.1.1.1 11.1.1.1 weight 9 maxconn 3server 1.1.1.1 1.1.1.1 weight 9 maxconn 3
backend www.oldboy2.orgserver 3.3.3.3 3.3.3.3 weight 20 maxconn 3000
backend www.oldboy20.orgserver 10.10.0.10 10.10.0.10 weight 9999 maxconn 33333333333
backend www.oldboy11.orgserver 2.2.2.2 2.2.2.2 weight 20 maxconn 3000
backend www.oldboy12.orgserver 2.2.2.2 2.2.2.2 weight 20 maxconn 3000
#查看
# 发 www.oldboy1.org #修改
# 发 [{'backend':'www.oldboy1.org','record':{'server':'1.1.1.1','weight':9,'maxconn':3}},{'backend':'www.oldboy1.org','record':{'server':'10.10.10.10','weight':99,'maxconn':33}}]#增加 删除
# 发 {'backend':'www.oldboy1.org','record':{'server':'1.1.1.1','weight':9,'maxconn':3}}import osdef file_handle(backend_data,res=None, type="fetch"):if type == "fetch":with open("haproxy.conf", "r") as read_f:tag = Falsel = []for r_l in read_f:if r_l.strip() == backend_data:tag = Truecontinueif tag and r_l.startswith("backend"):breakif tag:print("\33[1;45m %s \33[0m" % r_l, end="")l.append(r_l)return lelif type == "apend":with open("haproxy.conf", "r") as read_f, open("haproxy1.conf", "w") as write_f:for r_l in read_f:write_f.write(r_l)for n_l in res:write_f.write(n_l)os.rename("haproxy.conf", "haproxy.conf.bak")os.rename("haproxy1.conf", "haproxy.conf")os.remove("haproxy.conf.bak")elif type == "change":with open("haproxy.conf", "r") as read_f, open("haproxy1.conf", "w") as write_f:tag = Falsehas_write = Falsefor r_l in read_f:if r_l.strip() == backend_data:tag = Truecontinueif tag and r_l.startswith("backend"):tag = Falseif not tag:write_f.write(r_l)else:if not has_write:for n_l in res:write_f.write(n_l)has_write = Trueos.rename("haproxy.conf", "haproxy.conf.bak")os.rename("haproxy1.conf", "haproxy.conf")os.remove("haproxy.conf.bak")def fetch(data):backend_data = "backend %s" %datareturn file_handle(backend_data)def add(data):backend = data["backend"]backend_data = "backend %s" % backendn_r = "%sserver %s %s weight %s maxconn %s\n" % (" " * 8, data["record"]["server"],data["record"]["server"],data["record"]["weight"],data["record"]["maxconn"])res = fetch(backend)if not res:res.append(backend_data)res.append(n_r)file_handle(backend_data,type = "apend")else:res.insert(0,"%s\n"%backend_data)if n_r not in res:res.append(n_r)file_handle(backend_data, res, type="change")def remove(data):backend = data["backend"]backend_data = "backend %s"%backendc_r = "%sserver %s %s weight %s maxconn %s\n"%(" "*8,data["record"]["server"],data["record"]["server"],data["record"]["weight"],data["record"]["maxconn"])res = fetch(backend)if not res or c_r not in res:print("数据不存在")returnelse:res.insert(0,"%s\n"%backend_data)res.remove(c_r)file_handle(backend_data, res, type="change")def change(data):backend = data[0]["backend"]backend_data = "backend %s"%backendold_s_r = "%sserver %s %s weight %s maxconn %s\n"%(" "*8,data[0]["record"]["server"],data[0]["record"]["server"],data[0]["record"]["weight"],data[0]["record"]["maxconn"])new_s_r = "%sserver %s %s weight %s maxconn %s\n" % (" " * 8, data[1]["record"]["server"],data[1]["record"]["server"],data[1]["record"]["weight"],data[1]["record"]["maxconn"])res = fetch(backend)if not res or old_s_r not in res:print("数据不存在")returnelse:index = res.index(old_s_r)res[index] = new_s_rres.insert(0,"%s\n"%backend_data)file_handle(backend_data,res,type="change")if __name__ == "__main__":msg = '''1:查询2:添加3:删除4:修改5:退出'''menu_dic = {'1': fetch,'2': add,'3': remove,'4': change,'5': exit,}while True:print(msg)choice = input("请输入操作:").strip()if not choice or choice not in menu_dic:continueif choice == "5":breakdata = input("请输入数据:").strip()if choice != '1':data=eval(data)menu_dic[choice](data)