如何在Python中读取和写入INI文件

时间:2014-07-25 14:56:27

标签: python-2.7 configuration-files ini configparser

如何在Python 2.7中编辑INI文件

我正在尝试编辑已经包含我需要的章节和选项的INI配置文件。但是我需要根据wxPython中的checkboxlist更新值。目前一切正常:)但我觉得有更好的方法。以下是我正在使用的功能代码段的一部分。

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中的所有内容。

有没有办法只重写我正在改变的值?

这是我的第一个问题,所以如果我忘记提及某些事情,请告诉我。

还有一个信息点:   - 我查看了所有文档或者至少我能找到的文档   - 这是类似的,但不完全是我需要的    How to read and write INI file with Python3?

2 个答案:

答案 0 :(得分:1)

“有没有办法只重写我正在改变的价值?”不,因为它是一个文本文件。当你知道你正在编写的东西与你要替换的东西完全相同时,你只能进行选择性重写。这通常不是文本文件的情况,并且它们几乎从未被这样对待过。

我只对该功能进行了一次小型重组,以消除冗余:

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)

答案 1 :(得分:0)

由于文件的工作方式,一般情况下不可能。你不能"插入"字节到文件 - 你总是覆盖当前的内容。

只能使用相同长度的内容重写文件的某些部分,例如,当您想要将字符串"XXX"更改为"YYY"时。但这是一个很常见的做法,只是不用担心它,并在每次需要时将这些文件序列化为整体。

相关问题