python - 如何使用 python 修改配置文件?

标签 python python-2.7

我有一个cfg文件。在该 cfg 文件中有这样一行:

[Environment]
automation_type=GFX   ;available options: GEM, HEXAII

我想通过以下方式修改这一行:

[Environment]
automation_type=ABC   ;available options: GEM, HEXAII

我为此编写了以下代码:

get_path_for_od_cfg = r"C:\Users\marahama\Desktop\Abdur\abc_MainReleaseFolder\OD\od\odConfig.cfg"
    config = ConfigParser.RawConfigParser()
    config.read(get_path_for_OpenDebug_cfg)
    for sec in config.sections():
        for attr in config.options(sec):
            if sec =='Environment' and attr == 'automation_type':
                config.set('Environment','automation_type','ABC')
    with open(get_path_for_OpenDebug_cfg, 'wb') as configfile:
        config.write(configfile)

执行代码后,我得到

[Environment]
automation_type = ABC

";available options: GEM, HEXAII" this line is missing.

最佳答案

作为source code建议,在读取配置文件时,注释将被忽略,它们都在单独的行 ( 484 )...

if line.strip() == '' or line[0] in '#;':
     continue

和选项行 ( 522 ):

if vi in ('=', ':') and ';' in optval:
     # ';' is a comment delimiter only if it follows
     # a spacing character
     pos = optval.find(';')
     if pos != -1 and optval[pos-1].isspace():
         optval = optval[:pos]

所以我同意上面的评论,如果你关心保留评论,你应该切换到更低级别的东西。

关于python - 如何使用 python 修改配置文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16215842/

相关文章:

python - 如何在 python 中对字符串使用格式说明符

python - matplotlib 中同一循环的两个不同图?

python-2.7 - 运行Scrapy项目时无法导入名称

json 编码 - 为什么 utf8 和 utf-8 产生不同的输出?

python - 如何用唯一 ID 替换 Python Pandas 表文本值?

python - 如何将字符串格式的嵌套列表转换为列表(递归或迭代方式)

python-2.7 - 在python中将Twitter的日期格式转换为Datetime

python - pytorch中的autograd可以处理同一模块中层的重复使用吗?

python - 在 python 中返回解包列表

python - 检查键是否在字典中且值不为 None 的最 Pythonic 方法