[关闭]
@hainingwyx 2018-09-08T13:59:05.000000Z 字数 2272 阅读 1507

python 读取写入配置文件

python


Python 读取写入配置文件很方便,可使用内置的 configparser 模块。该模块支持读取配置文件,如 windows 下的 .conf 及 .ini 文件等。
例如:

  1. [db]
  2. db_port = 3306
  3. db_user = root
  4. db_host = 127.0.0.1
  5. db_pass = xgmtest
  6. [concurrent]
  7. processor = 20
  8. thread = 10

读取配置文件

read(filename) 直接读取文件内容
-sections() 得到所有的section,并以列表的形式返回
options(section) 得到该section的所有option
items(section) 得到该section的所有键值对
get(section,option) 得到section中option的值,返回为string类型
getint(section,option) 得到section中option的值,返回为int类型,还有相应的getboolean()和getfloat() 函数。

示例代码

  1. # !/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. import ConfigParser
  4. import os
  5. os.chdir("D:\\Python_config")
  6. cf = ConfigParser.ConfigParser()
  7. # cf.read("test.ini")
  8. cf.read("test.conf")
  9. #return all section
  10. secs = cf.sections()
  11. print 'sections:', secs, type(secs)
  12. opts = cf.options("db")
  13. print 'options:', opts, type(opts)
  14. kvs = cf.items("db")
  15. print 'db:', kvs
  16. #read by type
  17. db_host = cf.get("db", "db_host")
  18. db_port = cf.getint("db", "db_port")
  19. db_user = cf.get("db", "db_user")
  20. db_pass = cf.get("db", "db_pass")
  21. #read int
  22. threads = cf.getint("concurrent", "thread")
  23. processors = cf.getint("concurrent", "processor")
  24. print "db_host:", db_host
  25. print "db_port:", db_port
  26. print "db_user:", db_user
  27. print "db_pass:", db_pass
  28. print "thread:", threads
  29. print "processor:", processors
  30. ConfigParser

写入配置文件

write(fp) 将config对象写入至某个 .init 格式的文件 Write an .ini-format representation of the configuration state.
add_section(section) 添加一个新的section
set( section, option, value ) 对section中的option进行设置,需要调用write将内容写入配置文件 ConfigParser2
remove_section(section) 删除某个 section
remove_option(section, option) 删除某个 section 下的 option

示例代码

  1. import ConfigParser
  2. import os
  3. os.chdir("D:\\Python_config")
  4. cf = ConfigParser.ConfigParser()
  5. # add section / set option & key
  6. cf.add_section("test")
  7. cf.set("test", "count", 1)
  8. cf.add_section("test1")
  9. cf.set("test1", "name", "aaa")
  10. # write to file
  11. with open("test2.ini","w+") as f:
  12. cf.write(f)
  13. ConfigParser2

注意事项

参考文献

https://www.cnblogs.com/feeland/p/4514771.html
https://python3-cookbook.readthedocs.io/zh_CN/latest/c13/p10_read_configuration_files.html

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注