配置文件在python
根据所需的文件格式,有几种方法。
ConfigParser [.ini格式]
我将使用标准configparser方法,除非有令人信服的理由使用不同的格式。
写一个像这样的文件:
文件格式非常简单,带有方括号中的部分:
可以从文件中提取值,如:
JSON数据可以非常复杂,并且具有高度便携的优点。
将数据写入文件:
从文件读取数据:
提供了一个基本的YAML示例in this answer.更多细节可以在the pyYAML website找到。
根据所需的文件格式,有几种方法。
ConfigParser [.ini格式]
我将使用标准configparser方法,除非有令人信服的理由使用不同的格式。
写一个像这样的文件:
from ConfigParser import SafeConfigParser
config = SafeConfigParser()
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
可以从文件中提取值,如:
from ConfigParser import SafeConfigParser
config = SafeConfigParser()
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('config.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示例in this answer.更多细节可以在the pyYAML website找到。