Index error when trying to access list element


So I have a text document in csv style, like this:

Line number,1  
1,K1,O1,L1,L2,L3  
2,K2,O2,L2,L3  
3,K3,O3,L1,L3  
4,K4,O4,L2

I want to check if the number in the first line, after "Line number", is equal to the first element in one of the following lines. In this case this number can be 1, 2, 3 or 4.

My code is as follows:

import csv

lineNumber = 0

with open('B.txt', 'r') as f:

    reader = csv.reader(f, delimiter=",")

    for row in reader:
        if "Line Number" in row[0]:
            lineNumber = int(row[1]) <- not sure about this syntax btw
            print("Is equal")
            break

I end up with this error:

if "Line Number" in row[0]:
IndexError: list index out of range

Everything with row[n] seems to give an error.


Answer

There are 2 improvements to your code:

  1. Compare objects of the same type, e.g. int with int.
  2. Use next(reader) to extract the first row before your for loop.

This is one way you can refactor your logic:

import csv

with open('B.txt', 'r') as f:

    reader = csv.reader(f, delimiter=",")

    headers = next(reader)
    lineNumber = int(headers[1])

    for row in reader:
        if int(row[0]) == lineNumber:
            print("Is equal")
            break