Python攻克之路-configparser模块
configparser模块
描述:用于生成和修改常见配置文件,当前模块在python3.x中变更为configparser
常见的配置文件格式
描述:实际是多个字典的形式组成,[]中括号是一个键,下面的是它的值,值里也是字典,键值的形式
[root@python3 ~]# cat test [DEFAULT] #键 ServerAliveInterval = 45 #键 = 值 Commpression = yes CompressionLevel = 9 ForwardX11 = yes [lin.com] User = tom [reid.com] Port = 1002 ForwardX11 = no
使用Python生成配置文件
描述:写代码时,尽量不要把所有功能在一个脚本上实现,如信用卡,可以有信用卡本身的模块,进行存款,取款,转账等,还有购物车之类的,它要扣钱要到信用卡中扣钱,彼此之间shopping与atm就要分开,不能写在一个程序中,当购物需要一个结账时,只需要做一个接口把数据取到,是模块之间的调用,通过它来实现目录结构,在整个目录结构中,它需要有一个文件,一般是setting.py配置文件,如一般会存基本路径,如商品列表里有购物车,有mac, book等商品,这些数据可以放在配置文件中,以后关于数据的修改都在配置文件中修改,就不用操作执行程序,最终是模块之间的调用,把setting.py引到执行程序中,只能常变的配置修改.
[root@python3 ~]# cat config.py
#!/usr/local/python3/bin/python3
import configparser
config = configparser.ConfigParser() ##生成一个关于文件配置的对象
config['DEFAULT']={'ServerAliveInterval': '45', ##键 值
'Compression': 'yes',
'CompressionLevel': '9'}
config['DEFAULT']['ForwardX11']= 'yes'
config['lin.com'] = {'User': 'tom'}
config['reid.com'] = {'Port': '1002',
'ForwardX11': 'no'}
with open('reid.conf', 'w') as configfile: ##正式创建
config.write(configfile)
[root@python3 ~]#
[root@python3 ~]# cat reid.conf
[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes
[lin.com]
user = tom
[reid.com]
port = 1002
forwardx11 = no
操作实现
读文件
In [1]: import configparser
In [2]: config = configparser.ConfigParser()
In [3]: config.sections()
Out[3]: [] ##config对象是空的,所以这里是空的
In [4]: config.read('reid.conf') ##读,相当于关联起来
Out[4]: ['reid.conf']
In [5]: config.sections() ##
Out[5]: ['lin.com', 'reid.com']
In [6]: config.defaults() ##查看default的内容
Out[6]:
OrderedDict([('serveraliveinterval', '45'), ##ordereddict有序字典,在字典的基础上排序
('compression', 'yes'),
('compressionlevel', '9'),
('forwardx11', 'yes')])
判断
In [7]: 'lin.com' in config #是否在config Out[7]: True In [8]: 'redi.com' in config Out[8]: False
取值
In [9]: config['reid.com']['port'] #字典的操作 Out[9]: '1002'
使用for循环取内容
In [10]: for i in config: #取块
...: print(i)
...:
DEFAULT
lin.com
reid.com
In [11]: for i in config['reid.com']: #打印reid.com块下的内容时,还会打印default的内容
...: print(i)
...:
port
forwardx11
serveraliveinterval
compression
compressionlevel
删除块
In [12]: config.remove_section('reid.com')
Out[12]: True
In [13]: config.write(open('my.conf',"w")) #一个文件的内容固定了,是不能被修改,只能写到另一个文件,可以与之前的文件名称一样,但是是覆盖
[root@python3 ~]# cat my.conf
[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes
[lin.com]
user = tom
删除块下的键
In [17]: config.remove_option('lin.com','user') # 块 键
Out[17]: True
In [18]: config.write(open('my.conf',"w"))
判断是否有此字符串
In [14]: config.has_section('reid.com')
Out[14]: False
修改
In [15]: config.set('lin.com','user','jerry')
In [16]: config.write(open('my.conf',"w"))
[root@python3 ~]# cat my.conf
[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes
[lin.com]
user = jerry ######

浙公网安备 33010602011771号