Reputation: 127
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()
Upvotes: 7
Views: 8939
Reputation: 184
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)
Upvotes: 4
Reputation: 1235
I ran into this problem to and I came up with an additional solution.
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 ) )
Upvotes: 14
Reputation: 4719
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:
RawConfigParser
's write
method with your ownIf 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: 0