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)
?