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: lineNumber = int(row) <- not sure about this syntax btw print("Is equal") break
I end up with this error:
if "Line Number" in row: IndexError: list index out of range
Everything with row[n] seems to give an error.
There are 2 improvements to your code:
- Compare objects of the same type, e.g.
next(reader)to extract the first row before your
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) for row in reader: if int(row) == lineNumber: print("Is equal") break