1. 程式人生 > >Python3.x 文件操作練習

Python3.x 文件操作練習

bind mat daemon 中一 logs defaults 字典 rec __name__

# 要求

1.可在配置文件中添加一條記錄

2.可刪除配置文件中一條記錄

# 增加:

1.用戶輸入以下字典類型的字符串(註意字串必須要用雙引號"",因為json不能識別單引號)

"u_input = input({"backend": "test.aa.com", "record": {"server": "100.1.7.213", "weight": 20, "maxconn": 30}})"

2.通過json.loads()模塊把字符串轉換成字典

3.通過格式化配置文件,在需要添加的位置設置value的值

# 刪除:

1.選擇用戶輸入需要刪除的字符串,用strip()方法去除掉特殊符號

2.按行讀取配置文件,對比並排除需要刪除的字符串,把排除後的數據存入列表中

3.用"w"模式打開文件(把原來文件的內容清除),循環讀取列表內容,並寫入文件

配置文件:(文件名:config.txt)
---------------------------
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 aa.org
        bind 0.0.0.0:80
        option httplog
        option httpclose
        option  forwardfor
        log global
        acl www hdr_reg(host) -i www.aa.com
        use_backend www.aa.com if www

backend www.bb.com
        server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000

        # 格式化顯示
        # server": "{0}","weight": {1},"maxconn": {2}

backend buy.cc.com
        server 100.1.7.90 100.1.7.90 weight 20 maxconn 3000
---------------------------

 1 import json
 2 
 3 
 4 def add():
 5     ‘‘‘
 6    添加一條數據
 7    :return: 
 8    ‘‘‘
 9     # {"backend": "test.aa.com", "record": {"server": "100.1.7.213", "weight": 20, "maxconn": 30}}
10     u_input = input("Please input add data:")
11     dic = json.loads(u_input)
12 
13     server = dic["record
"]["server"] 14 weight = dic["record"]["weight"] 15 maxconn = dic["record"]["maxconn"] 16 17 with open("config.txt", r, encoding=utf-8) as f: 18 file = f.read() 19 result = file.format(server, weight, maxconn) 20 print(file) 21 print("=================" * 4) 22 23 with open("config.txt", w, encoding=utf-8) as f: 24 f.write(result) 25 print(result) 26 27 28 def dele(): 29 ‘‘‘ 30 刪除一條數據 31 :return: 32 ‘‘‘ 33 # u_input = input("Please input del data:") 34 add_list = [] 35 with open(config.txt, r)as f: 36 print("config files:") 37 for item in f.readlines(): 38 print("\n%s" % item.strip("\n")) 39 40 file = input("\n\n請輸入需要刪除的行數據:") 41 f.seek(0) 42 for item in f.readlines(): 43 if item.strip() != file.strip(): 44 add_list.append(item) 45 46 with open(config.txt, w, encoding=utf-8) as f: 47 f.writelines(add_list) 48 print("\n\n刪除行:‘%s‘\n完成!!!" % file.strip()) 49 50 51 if __name__ == __main__: 52 num = int(input("請選擇數字:\n【1】添加一條數據\n【2】刪除一條數據\n")) 53 if num == 1: 54 add() 55 elif num == 2: 56 dele()

Python3.x 文件操作練習