6

I am using a file and i have one section named DIR in which it contain the paths. EX:

[DIR]
DirTo=D:\Ashish\Jab Tak hai Jaan
DirBackup = D:\Parser\ERICSSON_CSCORE_STANDARD_VMS\Backup
ErrorDir = D:\Parser\ERICSSON_CSCORE_STANDARD_VMS\Error

CombinerDir = D:\Parser\ERICSSON_CSCORE_STANDARD_VMS\Combiner
DirFrom=D:\Parser\ERICSSON_CSCORE_STANDARD_VMS\In
PidFileDIR = D:\Parser\ERICSSON_CSCORE_STANDARD_VMS\Pid
LogDir = D:\Parser\ERICSSON_CSCORE_STANDARD_VMS\Log   
TempDir = D:\Parser\ERICSSON_CSCORE_STANDARD_VMS\Temp

Now I want to replace the paths which I have done it but when I replaced its giving me spaces after and before the delimiter in the newly written .ini file. For example: DirTo = D:\Parser\Backup. How I remove these spaces?

Code:

def changeINIfile():
    config=ConfigParser.RawConfigParser(allow_no_value=False)
    config.optionxform=lambda option: option
    cfgfile=open(r"D:\Parser\ERICSSON_CSCORE_STANDARD_VMS\Windows\opx_PAR_GEN_660_ERICSSON_CSCORE_STANDARD_PM_VMS_MALAYSIA.ini","w")
    config.set('DIR','DirTo','D:\Ashish\Jab Tak hai Jaan')
    config.optionxform=str
    config.write(cfgfile)
    cfgfile.close()
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Vipin Pulyani
  • 117
  • 1
  • 3
  • 7
  • 1
    Please post the code you are using to write these lines of text. Martijn Pieters correctly suggests that you can use `strip()` to remove whitespace from the start and end of a string, but a code sample would help us debug better. – Martin Foot Dec 24 '12 at 12:04
  • Please [edit] your question to update it with code. – Martijn Pieters Dec 24 '12 at 12:12
  • Use [raw strings](http://docs.python.org/2/reference/lexical_analysis.html#literals) or double escape your \, or use `os.path.join` for your paths. Also, as I see it the Python code is not creating any extra spaces, so what exactly is your question? – Burhan Khalid Dec 24 '12 at 12:19
  • I cannot reproduce your problem; no whitespace is added when I use your `.set()` call. Or did you mean the spaces around the ` = ` equals? Those are part of the format; the standard `.ini` file format allows for those spaces. – Martijn Pieters Dec 24 '12 at 12:21
  • Note that the Win32 INI parser will ignore this whitespace (it has some rather interesting behaviour, but that at least is one sensible one). So it may not actually be a problem for you beyond cosmetics. – Chris Morgan Dec 24 '12 at 13:22
  • @Martijn: there may be differences between setting and adding values; I can't remember clearly with configparser. – Chris Morgan Dec 24 '12 at 13:25
  • @ChrisMorgan: I tried both. – Martijn Pieters Dec 24 '12 at 14:14
  • You could also use sômething like `iniparse`. – Chris Morgan Dec 24 '12 at 21:40

3 Answers3

14

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 ) )
Joshua
  • 1,185
  • 14
  • 23
  • Most elegant and flexible solution. The write function can easily be extended to perform other kinds of filtering. – MarcH Oct 26 '14 at 18:17
  • 1
    I would use write.replace(" = ", "=", 1) so you don't change any values that happen to have " = " in them – linuts Feb 29 '16 at 11:29
  • The simple replace() above may change comments or even section names. To see how `crudini --ini-options=nospace ...` implements this replacement see https://github.com/pixelb/crudini/commit/65ace170 – pixelbeat Jul 20 '22 at 22:29
2

I know it's a very old question but the latest version of Configparser has simple solution. Just use:

parser.write(file_pointer, space_around_delimiters=False)

pixelbeat
  • 30,615
  • 9
  • 51
  • 60
Naveen Kumar
  • 164
  • 1
  • 4
  • 9
0

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")
0eggxactly
  • 4,642
  • 1
  • 16
  • 16
  • Hi Slace..Yup the 3 solution worked for me..thankyou so much :) – Vipin Pulyani Dec 25 '12 at 04:10
  • 4
    In Python 3, you can use `config.write(file_on_disk, space_around_delimiters=False)`. See [Python 3 Documentation: configparser.write](http://docs.python.org/3/library/configparser.html#configparser.ConfigParser.write) – Jonas Gröger Nov 16 '13 at 00:00