day⑥:configparser模块

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了day⑥:configparser模块相关的知识,希望对你有一定的参考价值。

用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser

一.生成一个configpaser文档
  1. #!/usr/bin/env python
  2. #coding=utf-8
  3. __author__ = ‘yaobin‘
  4. #生成一个configparse文档
  5. import configparser
  6. config = configparser.ConfigParser()
  7. #生成第一个节段
  8. config["DEFAULT"] = {‘ServerAliveInterval‘: ‘45‘,
  9. ‘Compression‘: ‘yes‘,
  10. ‘CompressionLevel‘: ‘9‘}
  11. #生成第二个节段
  12. config[‘bitbucket.org‘] = {}
  13. config[‘bitbucket.org‘][‘User‘] = ‘hg‘
  14. config[‘bitbucket.org‘][‘passwd‘] = ‘123456‘
  15. #生成第三个节段
  16. config[‘topsecret.server.com‘] = {}
  17. topsecret = config[‘topsecret.server.com‘]
  18. topsecret[‘Host Port‘] = ‘50022‘ # mutates the parser
  19. topsecret[‘ForwardX11‘] = ‘no‘ # same here
  20. config[‘DEFAULT‘][‘ForwardX11‘] = ‘yes‘
  21. with open(‘example.ini‘, ‘w‘) as configfile:
  22. config.write(configfile)




二.读增删改
  1. #!/usr/bin/env python
  2. #coding=utf-8
  3. __author__ = ‘yaobin‘
  4. import configparser
  5. config = configparser.ConfigParser()
  6. config.read(‘example.ini‘)
  7. # ########## 读 ##########
  8. # secs = config.sections()
  9. # print(secs)
  10. # options = config.options(‘bitbucket.org‘)
  11. # print(options)
  12. # item_list = config.items(‘bitbucket.org‘)
  13. # print(item_list)
  14. # val = config.get(‘bitbucket.org‘,‘user‘)
  15. # val2 = config.getint(‘bitbucket.org‘,‘passwd‘)
  16. # print(val)
  17. # print(val2)
  18. # a="bitbucket.org" in config
  19. # print(a)
  20. #
  21. # b="bitbucket.orgno" in config
  22. # print(b)
  23. # d=config[‘bitbucket.org‘][‘User‘]
  24. # e=config[‘DEFAULT‘][‘Compression‘]
  25. # print(d)
  26. # print(e)
  27. # topsercret=config[‘topsecret.server.com‘]
  28. # print(topsercret[‘forwardx11‘])
  29. # print(topsercret[‘host port‘])
  30. # for key in config[‘bitbucket.org‘]:
  31. # print(key) #DEFAULT也打印出来了,DEFAULT是全局变量吧
  32. #print(config[‘bitbucket.org‘][‘ForwardX11‘]) #打印默认的出来了
  33. # ########## 改写 ##########
  34. # sec = config.remove_section(‘bitbucket.org‘)
  35. # config.write(open(‘a.cfg‘, "w"))
  36. # sec = config.has_section(‘bitbucket.org‘)
  37. # print(sec)
  38. # config.add_section(‘yaobin‘)
  39. # config.write(open(‘b.cfg‘, "w"))
  40. #
  41. # config.set(‘yaobin‘,‘k1‘,"11111")
  42. # config.write(open(‘c.cfg‘, "w"))
  43. #
  44. # config.remove_option(‘bitbucket.org‘,‘passwd‘)
  45. # config.write(open(‘d.cfg‘, "w"))





以上是关于day⑥:configparser模块的主要内容,如果未能解决你的问题,请参考以下文章

day7 补充模块configparser/hashlib

day6 ConfigParser模块 yaml模块

day⑥:logging模块

python-day6-configparser模块,xml.etree模块

python学习笔记-Day7(configparser模块shutil压缩与解压模块subprocess)

python-day27--configparser模块