基于ConfigParser模块,我如何过滤掉并从ini文件中抛出每条注释?
import ConfigParser
config = ConfigParser.ConfigParser()
config.read("sample.cfg")
for section in config.sections():
print section
for option in config.options(section):
print option, "=", config.get(section, option)
Run Code Online (Sandbox Code Playgroud)
例如.在上面基本脚本下面的ini文件中打印出更多注释行,如:
something = 128 ; comment line1
; further comments
; one more line comment
Run Code Online (Sandbox Code Playgroud)
我需要的是只有段名和纯键值对,没有任何注释.ConfigParser是以某种方式处理此问题还是应该使用regexp ...或?干杯
根据docs行开头;或#将被忽略.您的格式似乎不满足该要求.你有没有机会改变输入文件的格式?
编辑:因为你不能修改你的输入文件,我建议你用一些东西预先解析它们:
tmp_fname = 'config.tmp'
with open(config_file) as old_file:
with open(tmp_fname, 'w') as tmp_file:
tmp_file.writelines(i.replace(';', '\n;') for i in old_lines.readlines())
# then use tmp_fname with ConfigParser
Run Code Online (Sandbox Code Playgroud)
显然,如果选项中存在分号,您必须更具创造性.
| 归档时间: |
|
| 查看次数: |
3913 次 |
| 最近记录: |