如何在INI文件中编写时删除空格 - Python

Vip*_*ani 4 python configparser python-2.7

我正在使用一个文件,我有一个名为DIR的部分,其中包含路径.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
Run Code Online (Sandbox Code Playgroud)

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

码:

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()
Run Code Online (Sandbox Code Playgroud)

Jos*_*hua 10

我遇到了这个问题,我想出了一个额外的解决方案.

  • 我不想替换该函数,因为未来的Python版本可能会改变RawConfigParser的内部函数结构.
  • 我也不想在写完之后立即阅读该文件,因为这看起来很浪费

相反,我在文件对象周围编写了一个包装器,它在所有写入的行中简单地将"="替换为"=".

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 ) )
Run Code Online (Sandbox Code Playgroud)


Dev*_*ant 0

这是 的定义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")
Run Code Online (Sandbox Code Playgroud)

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

  1. 使用 INI 文件,等号周围有空格
  2. 用你自己的方法覆盖RawConfigParser的方法write
  3. 写入文件,读取文件,删除空格,然后再次写入

如果您 100% 确定选项 1 不可用,可以采用以下方法执行选项 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")
Run Code Online (Sandbox Code Playgroud)

  • 在 Python 3 中,您可以使用 config.write(file_on_disk, space_around_delimiters=False)`。请参阅[Python 3文档:configparser.write](http://docs.python.org/3/library/configparser.html#configparser.ConfigParser.write) (4认同)