使用ConfigParser可以助您一臂之力!链接的文档在使用它进行编程时应该会非常有用。
对您来说,最有用的想法可能是示例,可以在此处找到。可以在下面找到编写配置文件的简单程序
import configparser
config = configparser.ConfigParser()
config['DEFAULT'] = {'ServerAliveInterval': '45',
'Compression': 'yes',
'CompressionLevel': '9'}
config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Port'] = '50022' # mutates the parser
topsecret['ForwardX11'] = 'no' # same here
config['DEFAULT']['ForwardX11'] = 'yes'
with open('example.ini', 'w') as configfile:
config.write(configfile)
Run Code Online (Sandbox Code Playgroud)
该程序会将一些信息写入文件“ example.ini”。读取此程序:
import configparser
config = configparser.ConfigParser()
config.read('example.ini')
print(config.sections()) #Prints ['bitbucket.org', 'topsecret.server.com']
Run Code Online (Sandbox Code Playgroud)
然后,您可以像使用其他任何词典一样简单地使用它。访问类似的值:
config['DEFAULT']['Compression'] #Prints 'yes'
Run Code Online (Sandbox Code Playgroud)
归功于python docs。