Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting specific line and value with Python DictReader

Tags:

python

csv

I have a csv file and am trying to get one specific value on, say, line 20, column 3.

But so far, all I managed is to display all values on column 3 (here called "name").

Here is my Python code

d = DictReader(r.csv().split('\n'))
for line in d:
    score = line["name"]
    print score

How can I display and get the value for only a specific line?

like image 783
Timothée HENRY Avatar asked Feb 02 '11 15:02

Timothée HENRY


2 Answers

Naive solution:

  target_row = 5
  for num, line in enumerate(d):
      if num == target_row:
          print line["name"]
          break

I removed the intermediate variable score.

Note that this is non-optimal, as you iterate until you reach the desired row, but I don't know if there is random access to lines in the DictReader.

like image 164
Andrea Spadaccini Avatar answered Nov 03 '22 00:11

Andrea Spadaccini


Skipping ahead to the desired line, just as in the other answer, but with slicing on the CSV-reading iterator instead of a manual loop:

import csv, itertools
rownum = 20
colname = "name"
line = itertools.islice(d, rownum - 1, rownum).next()
score = line[colname]

(Not the most beautiful code, I know, but that's just to illustrate the point.)

like image 29
earl Avatar answered Nov 03 '22 00:11

earl