5

私はファイルを使用していますが、パスが含まれているDIRという名前のセクションが1つあります。元:

[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。これらのスペースを削除するにはどうすればよいですか?

コード:

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

3 に答える 3

12

私はこの問題に遭遇し、追加の解決策を思いつきました。

  • 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 ) )
于 2014-08-01T15:52:19.777 に答える
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")

ご覧のとおり、%s = %s\n形式は関数にハードコードされています。あなたの選択肢は次のとおりだと思います:

  1. 等号の前後に空白を含む INI ファイルを使用する
  2. RawConfigParserwriteメソッドを独自のもので上書きする
  3. ファイルを書き込み、ファイルを読み取り、空白を削除して、もう一度書き込みます

オプション 1 が利用できないことが 100% 確実な場合は、オプション 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")
于 2012-12-24T15:25:25.453 に答える