首页 > 解决方案 > 删除两个特定行号之间的所有行

问题描述

我需要根据行号删除与其他行之间的所有行。在这个 file.py 中,我怎样才能删除 2º 和 6º 行之间的所有文件?

文件 :

1
2
3
4
5
6
7
8
9
10

使用此代码,我可以删除特定行的上方和/或下方的所有行。但是我不能

代码 :

with open('file.py', 'r') as fin:
    data = fin.read().splitlines(True)
    with open('ab.py', 'w') as fout:
        fout.writelines(data[2:])

我尝试了第二个代码,我只能删除 1 个特定行(当我尝试删除超过 1 个时,它效果不佳)

del_line1 = 1   
with open("file.py","r") as textobj:
    list = list(textobj)   
del list[del_line1 - 1]    
with open("file.py","w") as textobj:
   for n in list:
        textobj.write(n)

标签: pythonpython-3.xwith-statement

解决方案


这比预期的要容易。

dellist = [3, 4, 7] #numbers of the lines to be deleted

with open('data.txt') as inpf:
    with open('out.txt', 'w') as of:
        for i, line in enumerate(inpf):
            if i+1 not in dellist: #i+1 because i starts from 0
                of.write(line)

您读取每一行,如果行号不在禁止行列表中,则将该行写入另一个文件。

因此,假设您的原始输入,上面的代码给出:

1
2
5
6
8
9
10

注意:这里我调用了文件data.txt,最好.py只对内部有python代码的文件使用扩展名。


推荐阅读