简体   繁体   English

删除两个特定行号之间的所有行

[英]Delete all lines between two specific line numbers

I need to delete all lines bewtwen to other lines, based on the line numbers. 我需要根据行号删除其他行之后的所有行。 In this file.py, how could i delete all files betwen the 2º and the 6º line ? 在此file.py中,如何删除2º和6º行之间的所有文件?

file : 文件:

1
2
3
4
5
6
7
8
9
10

With this code i can delete all lines above and/or bellow of an specific line. 使用此代码,我可以删除特定行上方和/或下方的所有行。 But i cannot 但是我不能

code : 代码:

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

I tried this second code, where i can delete only 1 specific line ( when i tried to delete more then 1 it didn't work very well) 我尝试了第二个代码,在这里我只能删除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)

It's easier than expected. 它比预期的容易。

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)

You read each line, and if the line number is not in the list of prohibited lines, the line is written to another file. 您读取了每一行,并且如果该行号不在禁止行列表中,则该行将被写入另一个文件。

So assuming your original input, the code above gives: 因此,假设您的原始输入,上面的代码给出:

1
2
5
6
8
9
10

Note: here I called the file data.txt , it's better to use the .py extension for files with python code inside only. 注意:这里我将文件称为data.txt ,最好仅对内部带有python代码的文件使用.py扩展名。

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

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