0

I have been reading the Python docs on the CSV module here: https://docs.python.org/2/library/csv.html

And I noticed that it does not mention any way for a reader object to return the number of the line it is currently reading, or which iteration it is currently at. This seems like it would be a widely needed functionality. So, I am wondering how one can do this:

reader = csv.DictReader(readFile)
    for row in reader:
        # do something 
        # now want to find the line number that row corresponds to

Or if that is not possible, why that is the case.

Luca
  • 467
  • 3
  • 13

1 Answers1

5

The reader object is an iterator, so you can always use enumerate to get the line number:

reader = csv.DictReader(readFile)
for line_number, row in enumerate(reader):
     # some code

enumerate also lets you specify a custom starting index:

for line_number, row in enumerate(reader, 2):
    # line number starts at 2

enumerate isn't only limited to the reader object of the csv module but works in general with iterables and iterators.

Moses Koledoye
  • 71,737
  • 8
  • 101
  • 114