How to remove spaces while writing in INI file- Python

放肆的年华 提交于 2019-12-01 19:25:37

Here is the definition of RawConfigParser.write:

def write(self, fp):
    """Write an .ini-format representation of the configuration state."""
    if self._defaults:
        fp.write("[%s]\n" % DEFAULTSECT)
        for (key, value) in self._defaults.items():
            fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
        fp.write("\n")
    for section in self._sections:
        fp.write("[%s]\n" % section)
        for (key, value) in self._sections[section].items():
            if key != "__name__":
                fp.write("%s = %s\n" %
                         (key, str(value).replace('\n', '\n\t')))
        fp.write("\n")

As you can see, the %s = %s\n format is hard-coded into the function. I think your options are:

  1. Use the INI file with whitespace around the equals
  2. Overwrite RawConfigParser's write method with your own
  3. Write the file, read the file, remove the whitespace, and write it again

If you're 100% sure option 1 is unavailable, here's a way to do option 3:

def remove_whitespace_from_assignments():
    separator = "="
    config_path = "config.ini"
    lines = file(config_path).readlines()
    fp = open(config_path, "w")
    for line in lines:
        line = line.strip()
        if not line.startswith("#") and separator in line:
            assignment = line.split(separator, 1)
            assignment = map(str.strip, assignment)
            fp.write("%s%s%s\n" % (assignment[0], separator, assignment[1]))
        else:
            fp.write(line + "\n")

I ran into this problem to and I came up with an additional solution.

  • I didn't want to replace the function as future versions of Python might change the internal function structures of RawConfigParser.
  • I also didn't want to read the file back in right after it was written because that seemed wasteful

Instead I wrote a wrapper around the file object which simply replaces " = " with "=" in all lines written though it.

class EqualsSpaceRemover:
    output_file = None
    def __init__( self, new_output_file ):
        self.output_file = new_output_file

    def write( self, what ):
        self.output_file.write( what.replace( " = ", "=", 1 ) )

config.write( EqualsSpaceRemover( cfgfile ) )
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!