1

fileInput consists of a csv file with some 30 rows and I want to access only the second row.

for row in csv.reader(fileInput):

I need to access the second row not the first one(first one contains col names). row[1] gives second column in row0?

only the second row not from the first row!

learncode
  • 1,105
  • 4
  • 18
  • 36
  • You can assign `csv.reader` to a variable `my_csv` and iterate through each line. To skip a line you can use `next` as mentioned in [this answer](http://stackoverflow.com/a/14257599/378704) –  Oct 31 '16 at 17:47

2 Answers2

1
r = csv.reader(f)
first_line = next(r)
second_line = next(r)
for line in r:
    print(line) #rest of the lines

reader returns an iterator: https://docs.python.org/3/library/csv.html#csv.reader

Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
  • I like this better than a `break` in `for` loop, but note that `StopIteration` may be raised – salezica Oct 31 '16 at 17:48
  • Yeah, but if there aren't at least two lines in the input then the question doesn't make any sense and an exception should be raised – Patrick Haugh Oct 31 '16 at 17:53
0

You might want to consider using DictReader. It'll handle the header for you and allow you to access the columns by name rather than index (which can help with keeping code readable).

eg.

import csv

with open('names.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    row = next(reader)
    print(row['first_name'], row['last_name'])
Dunes
  • 37,291
  • 7
  • 81
  • 97