Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove spaces while writing in INI file- Python

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()
like image 263
Vipin Pulyani Avatar asked Dec 24 '12 12:12

Vipin Pulyani


1 Answers

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 ) )
like image 152
Joshua Avatar answered Nov 03 '22 00:11

Joshua