我正在尝试编辑已经具有所需节和选项的INI配置文件。但是我需要根据wxPython中的复选框列表更新值。目前一切都在工作:),但是我觉得有更好的方法。这是我正在使用的功能片段的一部分。
def read_or_write_file(self, file, section, passed_option = None,
value = None, read = True):
if read:
with open(file) as configfile:
config = ConfigParser.RawConfigParser()
config.readfp(configfile)
options = config.options(section)
for option in options:
file_settings[option] = config.get(section, option)
else:
with open(file, 'r+') as configfile:
config = ConfigParser.RawConfigParser()
config.readfp(configfile)
config.set(section, passed_option, value)
with open(file, 'r+') as configfile:
config.write(configfile)
这完全按照我想要的方式工作,告诉它我想要读取或写入的内容,并且可以正常工作。但是else:
,我写入文件的部分似乎很奇怪。我必须先进行编辑,config
然后再重写中的所有内容configfile
。
有没有办法只重写我要更改的值?
这是我的第一个问题,所以如果我忘了提些什么,请告诉我。
还有一个信息点:-我看了所有文档,或者至少看了我能找到的内容-这很相似,但不完全是我所需要的内容如何使用Python3读写INI文件?
“有没有办法只重写我要更改的值?” 不,因为它是一个文本文件。只有在知道所写内容与被替换内容的长度完全相同时,您才能进行选择性重写。文本文件通常不是这种情况,而且几乎从来没有那样对待它们。
我只需要对该功能进行一次小的重组,以消除冗余:
def read_or_write_file(self, file, section, passed_option = None,
value = None, read = True):
config = ConfigParser.RawConfigParser()
with open(file) as configfile:
config.readfp(configfile)
if read:
options = config.options(section)
for option in options:
file_settings[option] = config.get(section, option)
else:
config.set(section, passed_option, value)
with open(file, 'w') as configfile:
config.write(configfile)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句