我有一个cfg文件.在该cfg文件中有一行如下:
[Environment]
automation_type=GFX ;available options: GEM, HEXAII
Run Code Online (Sandbox Code Playgroud)
我想通过以下方式修改此行:
[Environment]
automation_type=ABC ;available options: GEM, HEXAII
Run Code Online (Sandbox Code Playgroud)
我为此编写了以下代码:
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)
Run Code Online (Sandbox Code Playgroud)
执行代码后,我明白了
[Environment]
automation_type = ABC
Run Code Online (Sandbox Code Playgroud)
";available options: GEM, HEXAII" this line is missing.
Run Code Online (Sandbox Code Playgroud)
正如源代码建议的那样,在阅读配置文件时,注释会被忽略,两者都在不同的行上(484)......
if line.strip() == '' or line[0] in '#;':
continue
Run Code Online (Sandbox Code Playgroud)
并在选项行(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]
Run Code Online (Sandbox Code Playgroud)
所以我同意上面的评论说如果你关心保留评论,你应该切换到更低级别的东西.