python中的配置文件
根据所需的文件格式,有多种方法可以执行此操作。
ConfigParser [.ini 格式]
我会使用标准配置解析器 http://docs.python.org/2/library/configparser.html除非有令人信服的理由使用不同的格式。
像这样写一个文件:
# python 2.x
# from ConfigParser import SafeConfigParser
# config = SafeConfigParser()
# python 3.x
from configparser import ConfigParser
config = ConfigParser()
config.read('config.ini')
config.add_section('main')
config.set('main', 'key1', 'value1')
config.set('main', 'key2', 'value2')
config.set('main', 'key3', 'value3')
with open('config.ini', 'w') as f:
config.write(f)
文件格式非常简单,部分用方括号标记:
[main]
key1 = value1
key2 = value2
key3 = value3
可以像这样从文件中提取值:
# python 2.x
# from ConfigParser import SafeConfigParser
# config = SafeConfigParser()
# python 3.x
from configparser import ConfigParser
config = ConfigParser()
config.read('config.ini')
print(config.get('main', 'key1')) # -> "value1"
print(config.get('main', 'key2')) # -> "value2"
print(config.get('main', 'key3')) # -> "value3"
# getfloat() raises an exception if the value is not a float
a_float = config.getfloat('main', 'a_float')
# getint() and getboolean() also do this for their respective types
an_int = config.getint('main', 'an_int')
JSON [.json 格式]
JSON 数据可能非常复杂,但具有高度可移植的优点。
将数据写入文件:
import json
config = {"key1": "value1", "key2": "value2"}
with open('config1.json', 'w') as f:
json.dump(config, f)
从文件中读取数据:
import json
with open('config.json', 'r') as f:
config = json.load(f)
#edit the data
config['key3'] = 'value3'
#write it back to the file
with open('config.json', 'w') as f:
json.dump(config, f)
YAML
提供了一个基本的 YAML 示例在这个答案中 https://stackoverflow.com/a/1774043/1083707。更多详细信息可以参见pyYAML 网站 http://pyyaml.org/wiki/PyYAMLDocumentation.