2012-12-24 105 views
4

我正在使用一個文件,並且我有一個名爲DIR的部分,其中包含路徑。 EX:如何在INI文件中寫入時刪除空格 - Python

[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() 
+1

請發佈您正在使用的代碼來編寫這些文本行。 Martijn Pieters正確地建議您可以使用'strip()'從字符串的開頭和結尾刪除空格,但代碼示例可以幫助我們更好地進行調試。 –

+0

請[編輯]您的問題以更新代碼。 –

+0

使用[raw strings](http://docs.python.org/2/reference/lexical_analysis.html#literals)或雙重轉義您的\,或使用'os.path.join'作爲您的路徑。另外,正如我看到的那樣,Python代碼沒有創建任何額外的空間,那麼你的問題到底是什麼? –

回答

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. 寫入文件,讀取文件,刪除空白,並寫再次

如果你是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") 
+0

嗨Slace..Yup 3解決方案爲我工作..謝謝你這麼多:) –

+2

在Python 3中,你可以使用'config.write(file_on_disk,space_around_delimiters = False)'。請參閱[Python 3 Documentation:configparser.write](http://docs.python.org/3/library/configparser.html#configparser.ConfigParser.write) –

8

我遇到了這個問題,我想出了一個額外的解決方案。

  • 我不想替換函數,因爲未來的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)) 
+0

最優雅靈活的解決方案。寫入功能可以輕鬆擴展以執行其他類型的過濾。 – MarcH

+1

我會使用write.replace(「=」,「=」,1),所以你不要改變任何碰巧有「=」的值 – linuts

+0

好的,@linuts我編輯了答案以增加max replace count 1.這可能導致問題的唯一方法是密鑰中是否有相等值,但密鑰通常少於數據。 – Joshua

相關問題