2016-07-29 66 views
1

我有一個註釋文件列表,我需要刪除該文件(#)中的註釋行,並且需要在同一個文件上寫入。Python:如何刪除註釋行並寫入同一個文件?

註釋文件:

#Hi this the comment 
define host { 
     use    template 
     host_name  google_linux 
     address   192.168.0.12 
} 

#commented config 
#ddefine host { 
#d  use    template1 
#d  host_name  fb_linux 
#d  address   192.168.0.13 
#d} 

我寫刪除一個文件中的註釋行的代碼?

代碼:

>>> with open('commentfile.txt','r+') as file: 
...  for line in file: 
...  if not line.strip().startswith('#'): 
...    print line, 
...    file.write(line) 
... 
define host { 
     use    template 
     host_name  google_linux 
     address   192.168.0.12 
} 

>>> with open('commentfile.txt','r+') as file: 
...  for line in file: 
...  if line.strip().startswith('#'): 
...    continue 
...  print line, 
...  file.write(line) 
... 
define host { 
     use    template 
     host_name  google_linux 
     address   192.168.0.12 
} 

我嘗試使用上述兩種方法的打印輸出回到正確的,但能不能在同一個文件寫一遍。

輸出文件:

cat commentfile.txt 
#Hi this the comment 
    define host { 
      use    template 
      host_name  google_linux 
      address   192.168.0.12 
    } 

    #commented config 
    #ddefine host { 
    #d  use    template1 
    #d  host_name  fb_linux 
    #d  address   192.168.0.13 
    #d} 

預期輸出:

cat commentfile.txt 
define host { 
       use    template 
       host_name  google_linux 
       address   192.168.0.12 
     } 

我甚至試過正則表達式的方法,但沒有工作在同一個文件寫入。

RE方法:

for line in file: 
      m = re.match(r'^([^#]*)#(.*)$', line) 
      if m: 
       continue 

任何暗示將是有益的?

+4

在讀取文件時寫入文件非常棘手。最好將整個文件讀入內存,對其進行處理,然後一次性將其轉儲迴文件中。這並不是那麼大,所以消耗的內存並不重要。 – deceze

+1

如果它是一個小文件,請將整個文件讀入內存,關閉文件,執行處理並將其寫回。如果它是一個大文件,讀取文件,進程,同時寫入另一個文件,完成後,將臨時文件重命名爲原始文件。 – Vatine

+0

@deceze我在循環播放這些文件。但是有些文件也有2GB的配置數據,可以嗎?如果我遵循你的方法。 –

回答

0

我不認爲你可以寫一行文件,你正在循環,你需要寫出一個不同的文件,你可以在循環後移動原始文件。

或者,你可以閱讀所有線路,內存,關閉並重新打開該文件,並寫入了與新的加工線

0

一些僞線

打開的文件中讀取 打開寫一個新的文件模式調用它temp 循環並做一些操作(刪除註釋,添加你需要添加的東西)並寫入臨時文件 關閉原始文件並將其刪除 然後將臨時文件重命名爲舊文件 會像

fileVar = open(file, 'r') 
tempFile = open(file, 'w') 
for line in file: 
    # do your operations 
    #you could write at the same time 
    tempFile.write(linePostOperations) 
fileVar.close() 
os.remove(filePath) 
tempFile.close() 
os.rename(tempFileName, newFileName) 
相關問題