Python3.x 文件操作练习
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python3.x 文件操作练习相关的知识,希望对你有一定的参考价值。
# 要求
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()