python读取配置文件

配置文件:

配置文件使用[section]和key-value对来区分;

key:value和key=value都可以;

和;是注释行;

SafeConfigParser类可以实现插值;

[numbers]
pi:3.14159

[messages]
greeting: Welcome to the area calculation program!
question: Please enter the radius:
result_message: The area is:
**读取配置:**
from ConfigParser import ConfigParser

config = ConfigParser()
# 读取配置文件
config.read('c:/python/config.txt')

# 打印初始问候语'greeting'
# 要查看的区段是'messages'
print config.get('messages', 'greeting')

# 读取半径数值
radius = input((config.get('messages', 'question') + ' '))

print config.get('messages', 'result_message'),

# 打印结果
print (config.getfloat('numbers', 'pi') * radius**2)
**输出**
Welcome to the area calculation program!
Please enter the radius: 1.2
The area is:
4.5238896
**写配置**
import ConfigParser

config = ConfigParser.RawConfigParser()

# When adding sections or items, add them in the reverse order of
# how you want them to be displayed in the actual file.
# In addition, please note that using RawConfigParser's and the raw
# mode of ConfigParser's respective set functions, you can assign
# non-string values to keys internally, but will receive an error
# when attempting to write to a file or when you get it in non-raw
# mode. SafeConfigParser does not allow such assignments to take place.
config.add_section('Section1')
config.set('Section1', 'an_int', '15')
config.set('Section1', 'a_bool', 'true')
config.set('Section1', 'a_float', '3.1415')
config.set('Section1', 'baz', 'fun')
config.set('Section1', 'bar', 'Python')
config.set('Section1', 'foo', '%(bar)s is %(baz)s!')

# Writing our configuration file to 'example.cfg'
with open('example.cfg', 'wb') as configfile:
    config.write(configfile)
**关于插值:**
foo = %(bar)s is %(baz)s!
print (config.get('Section1', 'foo', 0, {'bar': 'Documentation',
                                        'baz': 'evil'}))
输出为:
Documentation is evil!
坚持原创技术分享,您的支持将鼓励我继续创作!