2015-07-01 172 views
0

我有格式化像這樣的文件:刪除文件行蟒蛇

#1 0.13297254902 0.324803921569 0.434835294118 ...#many floats in one line 
#2 0 
#3 0.377305882353 0.595870588235 0.353215686275 ... 
#4 1 #0/1 for the second line 
#5 .... 

我要處理的文件,以便與第二行中的所有塊爲0可以被刪除,留下的文件

#1 0.377305882353 0.595870588235 0.353215686275 ... 
#2 1 
#3 0.403529411765 0.341654901961 0.379278431373 ... 
#4 1 #now they are all 1s 
#5 ..... 

我試過下面的代碼片斷,但它只能看到0/1然後刪除該行,但我想刪除0/1上面的浮動行,而不是0/1下面的浮動行。

​​

有沒有其他辦法可以選擇哪條線包括哪條線? 或者也許有辦法反向處理文件?

回答

2

我們可以使用next()函數來獲取文件迭代中的下一個元素。 shutil模塊允許我們移動新文件,覆蓋原文(謝謝@JoranBeasley)。

import shutil 

with open(filePath, 'r') as f, open('new_' + filePath, 'w') as output: 
    for line in f: 
     n = next(f) 
     if n != '0\n': 
      output.write(line+n) 

shutil.move("new_" + filePath, filePath) 

輸入:

0.13297254902 0.324803921569 0.434835294118 ...#many floats in one line 
0 
0.377305882353 0.595870588235 0.353215686275 ... 
1 #0/1 for the second line 

輸出:

0.377305882353 0.595870588235 0.353215686275 ... 
1 #0/1 for the second line 
+0

呀,它的作品!但是可以將它們存儲到同一個文件中嗎? – Mandary

+1

'shutil.move(「new_filepath.txt」,filepath)'? –

+0

Mandary:您可以使用['fileinput'](https://docs.python.org/3/library/fileinput.html#module-fileinput)模塊進行相對簡單的就地文件修改。 – martineau