Skip to main content
 首页 » 编程设计

Python之ConfigParser 抛出评论

2025年05月04日10kuangbin

基于 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) 

例如。在上面的基本脚本下面的 ini 文件中打印出进一步的注释行,如:

something  = 128     ; comment line1 
                      ; further comments  
                       ; one more line comment 

我需要的是其中只有部分名称和纯键值对,没有任何注释。 ConfigParser 是否以某种方式处理这个问题,或者我应该使用正则表达式......还是?干杯

请您参考如下方法:

根据 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 

显然,如果分号出现在选项中,您就必须更有创意。