2015-07-01 176 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