python 文件处理

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 文件

global
        log 127.0.0.1 local2
        daemon
        maxconn 256
        log 127.0.0.1 local2 info
defaults
        log global
        mode http
        timeout connect 5000ms
        timeout client 50000ms
        timeout server 50000ms
        option  dontlognull

listen stats :8888
        stats enable
        stats uri       /admin
        stats auth      admin:1234

frontend oldboy.org
        bind 0.0.0.0:80
        option httplog
        option httpclose
        option  forwardfor
        log global
        acl www hdr_reg(host) -i www.oldboy.org
        use_backend www.oldboy.org if www

backend www.oldboy1.org
        server 1.1.1.1 1.1.1.1 weight 999 maxconn 333
        server 11.1.1.1 11.1.1.1 weight 9 maxconn 3
        server 1.1.1.1 1.1.1.1 weight 9 maxconn 3
backend www.oldboy2.org
        server 3.3.3.3 3.3.3.3 weight 20 maxconn 3000
backend www.oldboy20.org
        server 10.10.0.10 10.10.0.10 weight 9999 maxconn 33333333333
backend www.oldboy11.org
        server 2.2.2.2 2.2.2.2 weight 20 maxconn 3000
backend www.oldboy12.org
        server 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 os

def file_handle(backend_data,res=None, type="fetch"):
    if type == "fetch":
        with open("haproxy.conf", "r") as read_f:
            tag = False
            l = []
            for r_l in read_f:
                if r_l.strip() == backend_data:
                    tag = True
                    continue
                if tag and r_l.startswith("backend"):
                    break
                if tag:
                    print("33[1;45m %s 33[0m" % r_l, end="")
                    l.append(r_l)
            return l
    elif 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 = False
            has_write = False
            for r_l in read_f:
                if r_l.strip() == backend_data:
                    tag = True
                    continue
                if tag and r_l.startswith("backend"):
                    tag = False
                if not tag:
                    write_f.write(r_l)
                else:
                    if not has_write:
                        for n_l in res:
                            write_f.write(n_l)
                        has_write = True

        os.rename("haproxy.conf", "haproxy.conf.bak")
        os.rename("haproxy1.conf", "haproxy.conf")
        os.remove("haproxy.conf.bak")

def fetch(data):

    backend_data = "backend %s" %data
    return file_handle(backend_data)

def add(data):
    backend = data["backend"]
    backend_data = "backend %s" % backend
    n_r = "%sserver %s %s weight %s maxconn %s
" % (" " * 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
"%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"%backend
    c_r = "%sserver %s %s weight %s maxconn %s
"%(" "*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("数据不存在")
        return
    else:
        res.insert(0,"%s
"%backend_data)
        res.remove(c_r)
        file_handle(backend_data, res, type="change")


def change(data):
    backend = data[0]["backend"]
    backend_data = "backend %s"%backend

    old_s_r = "%sserver %s %s weight %s maxconn %s
"%(" "*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
" % (" " * 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("数据不存在")
        return
    else:
        index = res.index(old_s_r)
        res[index] = new_s_r
    res.insert(0,"%s
"%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:continue
        if choice == "5":break

        data = input("请输入数据:").strip()
        if choice != '1':
            data=eval(data)
        menu_dic[choice](data)
原文地址:https://www.cnblogs.com/liaoboshi/p/6136257.html