user1312155
user1312155

Reputation: 173

What needs to be added in code to remove spaces in config file?

i have a config file and when i write into it it has spaces in it

Upvotes: 1

Views: 482

Answers (1)

Mio Bambino
Mio Bambino

Reputation: 544

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")

Upvotes: 4

Related Questions