简体   繁体   中英

Delete N lines of file

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)

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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