gpt4 book ai didi

Python - ConfigParser 抛出评论

转载 作者:太空宇宙 更新时间:2023-11-04 06:58:19 27 4
gpt4 key购买 nike

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

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

关于Python - ConfigParser 抛出评论,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/564662/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com