繁体   English   中英

从python文件中删除行

[英]delete lines from file in python

我有一个格式如下的文件:

#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  ....

我想处理该文件,以便第二行的所有块都可以被删除,并将文件保留为

#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的行。

f = open(filePath, "r")
lines = f.readlines()
f.close()
f = open(filePath, "w")

for line in lines:
    if "1\n" in line:
        f.write(line)

还有什么其他方法可以选择要包括哪些行,哪些不可以? 也许有一种方法可以向后处理文件?

我们可以使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM