Home > Back-end >  Delete N lines of file
Delete N lines of file

Time:10-29

I have the following .txt file:

28563868423
37832070256
49953540371
39723132411
48576892756
49159435134
49580970815
50007496483
8122645142

For example, I want to delete with the length of "id" (the first 3 lines).

But when I do that it deletes the first and fourth line.

id=[[''],[''],['']]

lines=[]
with open('Id.txt','r') as f:
    lines=f.readlines()

with open('Id.txt','w') as f:
    for number,line in enumerate(lines):
        if number not in [0,len(id)]:
            f.write(line)

CodePudding user response:

When you use [0, len(id)] you're effectively creating a list with two items - 0 and len(id). It seems you're interested in the range of numbers from 0 to len(id) - so range(len(id)) would be what you're looking for.
If you are always interested in eliminating the first N rows, you could also simply check for row numbers that are equal or larger then len(id) - if number >= len(id): ....

However, a more Pythonic and efficient solution would be to use list slicing. You can select all rows starting at len(id) with lines[len(id):]. See Python's Introduction to Lists where the slicing notation is introduced.

CodePudding user response:

in [0,len(id)] literally checks if it's the first or len(id)-th line. For the desired result, the check should be:

if number >= len(id):
    ...

or, even better, replace it with array slicing:

for line in lines[len(id):]:
    f.write(line)
  • Related