本文介绍了如何在INI文件中写入时删除空格 - Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个文件,我有一个名为 DIR 的部分,其中包含路径.例如:

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

现在我想替换我已经完成的路径,但是当我替换它时,在新编写的 .ini 文件中的分隔符前后给我空格.例如:DirTo = D:\Parser\Backup.我如何删除这些空格?

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?

代码:

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

推荐答案

这里是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")

如您所见,%s = %s\n 格式被硬编码到函数中.我认为您的选择是:

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

  1. 使用等号周围有空格的 INI 文件
  2. 用你自己的覆盖RawConfigParserwrite方法
  3. 写文件,读文件,去掉空格,再写

如果您 100% 确定选项 1 不可用,请执行选项 3:

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

这篇关于如何在INI文件中写入时删除空格 - Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 15:48