python对文件的增删改查

python对配置文件操作,对文件的增\删\改\查,分享下思路

分享下思路:

  1. 首先打印操作选择菜单,让用户选择对文件进行什么操作
  2. 根据不同的选择执行不同的操作:
    • 搜索:用户输入的域名,将域名下面的数据拼接起来,然后输出到文件
    • 删除:用户输入域名、server、weight吧啦吧啦,然后处理字符串,然后用用户输入的内容与字符串进行匹配,假如匹配成功,则不拼接这一行
    • 添加:根据用户输入的域名,在域名下面拼接进用户输入的server、weight吧啦吧啦
    • 修改:根据用户输入的吧啦吧啦,匹配到与用户输入相同的吧啦吧啦的哪一行,然后,然后将字符串拼接进用户输入的吧啦吧啦
  3. 得到修过过的文件内容后,新建文件,然后重命名成源文件 文件数据结构

backend www.heihei1.org
        server 10.10.10.1 10.10.10.1 weight 22 maxconn 2000
        server 10.10.0.10 10.10.0.10 weight 9999 maxconn 33
        server 2.2.2.4 2.2.2.4 weight 20 maxconn 3000

backend www.heihei2.org
        server 3.3.3.3 3.3.3.3 weight 20 maxconn 3000

backend www.heihei20.org
        server 10.10.0.10 10.10.0.10 weight 9999 maxconn 33

python操作代码

#!/bin/python3
# -*- coding:utf-8 -*-
import os
#functions
def get_input(file1,type1):
    'get choice and get user input return list'
    list1 = []
    while True:
        domain_name = input("domain name:")
        for x in file1:
            if domain_search(domain_name, x):
                file1.seek(0)
                break
        else:
            print("no domainname matched")
            file1.seek(0)
            continue
        list1.append(domain_name)
        if type1 in ['2','3']:
            #delete or  add
            server_str = input("input server:")
            weight_str = input("input weight:")
            maxcon_str = input("input maxcon:")
            temp_list = [server_str,weight_str,maxcon_str]
            list1.extend(temp_list)
            return list1
        if type1 == '4':
            # modify
            while True:
                server_str = input("input oldlist(server weight maxcon):")
                weight_str = input("input newlist:")
                server_str = str_rebuild(server_str)
                weight_str = str_rebuild(weight_str)
                if len(server_str) == 3 and len(weight_str) == 3:
                    list1.extend(server_str)
                    list1.extend(weight_str)
                    return list1
        return list1
def str_rebuild(str1):
    'get str1 >> strip >> splip return list'
    str1 = str1.strip()
    str1 = str1.split(" ")
    return str1
def domain_search(str1,str2):
    'find domain domain in file return t or f'
    flag = False
    if str2.startswith("backend") and str1 in str2:
        flag = True
    return flag
def search_str(list1,file1):
        'find input domain name in file return str'
        flag = False
        str1 = ""
        for x in file1:
                if domain_search(list1[0],x):
                        flag = True
                        continue
                if x.startswith("backend") and flag:
                        break
                if flag:
                        str1 += x
        file1.seek(0)
        return str1
def str_act(list1,file1,choice):
    'delete add modify and balabala... return str1'
    str1 = ""
    temp_str = ""
    flag = False
    for x in file1:
        if domain_search(list1[0], x):
            str1 += x
            flag = True
            continue
        if flag:
            if choice in ['2','4']:
                temp_str = str_rebuild(x)
                if list1[1] == temp_str[1] and list1[2] == temp_str[4] and list1[3] == temp_str[6]:
                    if choice == '2':
                        flag = False
                        continue
                    if choice == '4':
                        str1 += "        server %s %s weight %s maxconn %s\n" %(list1[4],list1[4],list1[5],list1[6])
                        flag = False
                        continue
            if choice == '3':
                str1 += "        server %s %s weight %s maxconn %s\n" %(list1[1],list1[1],list1[2],list1[3])
                flag = False
        str1 += x
    file1.seek(0)
    return str1

#Print Menu
print("%s\n%s\n%s" %("menu".center(20,"#"),"1. search\n2. delete\n3. add\n4. modify","menu".center(20,"#")))

#Main program
with open("haproxy.conf","r") as file_read,open("haproxy.conf.bak","w") as file_write:
    #get choose
    while True:
        choice = input(">")
        if choice[0] in ['1','2','3','4']:
            choice = choice[0]
            break
    input_list = get_input(file_read,choice)
    #search
    if choice == '1':
        str_res = search_str(input_list, file_read)
        if str_res:
            print(str_res)
        else:
            print("nothing found!")
    #delete
    if choice == '2':
        str_res = str_act(input_list, file_read,choice)
        print("writting...")
        file_write.write(str_res)
    #add
    if choice == '3':
        str_res = str_act(input_list, file_read,choice)
        print("add...")
        file_write.write(str_res)
    #modify
    if choice == '4':
        str_res = str_act(input_list, file_read,choice)
        print("modify...")
        file_write.write(str_res)
#file rename and replace
os.rename("haproxy.conf.bak", "haproxy.conf")

Leave a Reply

Your email address will not be published. Required fields are marked *