Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Understaning CSV Module and line_num object

In my code, I would like to be able to print the line number if an error is found during processing (called in another piece of code), but I'm having trouble doing this using the line_num object. Here is my code for a .csv that is 4 rows long:

with open(inFile, 'U') as inFH:
    csvReader = csv.reader(inFH, delimiter = ',')
    header = csvReader.__next__()
    lineNum = csvReader.line_num

    for row in csvReader:
        print(lineNum)

when I execute this code, I see this in the console:

1
1
1
1

My expectation is that I would see:

1
2
3
4

It almost looks like the code is printing the index and not the line number...

like image 782
Seth Avatar asked Dec 11 '22 10:12

Seth


1 Answers

lineNum is not changed after the first assignment. Printing it inside loop print same value repeatedly.

Why don't you print csvReader.line_num as follow?

for row in csvReader:
    print(csvReader.line_num)
like image 109
falsetru Avatar answered Dec 23 '22 09:12

falsetru