-1

I am very new to python. I am trying to create a script that prints lines of text to a text file that exclude a list of lines. Is the error IndexError : List index out of range due to the .pop function?

with open(file_path) as f:

    lines = []
    lines = open(f,'r').readlines() 

    # delete the following lines from the textfile
    skip_line =[14,27,39,56,78]

    while skip_line:
        pop = skip_line.pop(0)
        print(pop)
        print(lines[pop])

        lines.remove(lines[pop])

        with open('duplicates_removed.txt', 'w') as savefile:
                savefile.writelines(lines)
        savefile.close()

I expect that the lines found in lines[pop] will be removed from lines.

Actual result:

IndexError : List index out of range
a_guest
  • 34,165
  • 12
  • 64
  • 118
Sed Ward
  • 13
  • 2
  • Please include some sample text as well as the full error message (traceback). Most likely your test file has fewer lines than indicated in `skip_line`. Also note that you're opening the file two times and saving the other during each iteration of the while loop. – a_guest Apr 07 '19 at 22:34
  • The line `lines = open(f,'r').readlines()` is wrong and I'm surprised it doesn't raise an error. You already opened the file on the first line, you can just do `f.readlines()` but the pythonic way is to do `for line in f: do_something(line)`. – Boris Verkhovskiy Apr 07 '19 at 22:44
  • You shouldn't modify a list while you're iterating over it. After you delete the first line in `lines`, all the line indexes in `skip_line` that come after it are off by one. – Boris Verkhovskiy Apr 07 '19 at 23:36

1 Answers1

0
skip_lines = {14, 27, 39, 56, 78}

with open(filepath) as infile:
    with open("duplicates_removed.txt", "w") as outfile:
        for index, line in enumerate(infile):
            if index not in skip_lines:
                outfile.write(line)
Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
  • If you want to detect duplicate lines using Python instead of making a list of line numbers by hand, you should check out [this question](https://stackoverflow.com/questions/1215208/how-might-i-remove-duplicate-lines-from-a-file) or the dozens of others just like it. – Boris Verkhovskiy Apr 08 '19 at 18:49