python小白-day6 ConfigParser模块
ConfigParser模块
用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser。
来看一个好多软件的常见文档格式如下

用python生成上文档代码如下;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import configparserconfig = configparser.ConfigParser()config["DEFAULT"] = {'ServerAliveInterval': '45', 'Compression': 'yes', 'CompressionLevel': '9'}config['bitbucket.org'] = {}config['bitbucket.org']['User'] = 'hg'config['topsecret.server.com'] = {}topsecret = config['topsecret.server.com']topsecret['Host Port'] = '50022' # mutates the parsertopsecret['ForwardX11'] = 'no' # same hereconfig['DEFAULT']['ForwardX11'] = 'yes'with open('example.ini', 'w') as configfile: config.write(configfile) |
读文档:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | >>> import configparser>>> config = configparser.ConfigParser()>>> config.sections()[]>>> config.read('example.ini')['example.ini']>>> config.sections()['bitbucket.org', 'topsecret.server.com']>>> 'bitbucket.org' in configTrue>>> 'bytebong.com' in configFalse>>> config['bitbucket.org']['User']'hg'>>> config['DEFAULT']['Compression']'yes'>>> topsecret = config['topsecret.server.com']>>> topsecret['ForwardX11']'no'>>> topsecret['Port']'50022'>>> for key in config['bitbucket.org']: print(key)...usercompressionlevelserveraliveintervalcompressionforwardx11>>> config['bitbucket.org']['ForwardX11']'yes' |
删除bitbucket.org:
1 2 3 4 5 6 | import configparserconfig = configparser.ConfigParser()config.read('example.ini')config.remove_section('bitbucket.org')config.write(open('example.bak','w')) |

增加hetan:
1 2 3 4 5 6 7 8 | import configparserconfig = configparser.ConfigParser()config.read('example.ini')config.has_section('hetan')config.add_section('hetan')config['hetan']['age'] = "26"config.write(open('example.cfg','w')) |

修改hetan中的age为25:
1 2 3 4 5 6 | import configparserconfig = configparser.ConfigParser()config.read('example.cfg')config.set('hetan','age','25')config.write(open('example.cfg.bak','w')) |

删除hetan中的age:
1 2 3 4 5 6 | import configparserconfig = configparser.ConfigParser()config.read('example.cfg.bak')config.remove_option('hetan','age')config.write(open('example.cfg.bak2','w')) |

浙公网安备 33010602011771号