Timothée HENRY
Timothée HENRY

Reputation: 14614

Getting specific line and value with Python DictReader

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?

Upvotes: 6

Views: 12044

Answers (4)

tomatoeshift
tomatoeshift

Reputation: 485

if you only know the column number and the line number you can do like this:

TheRow = 2      # Note that row 1 is the header row
TheColumn = 2   # first column == 0
for row in d:
    if d.line_num == TheRow:
        print("row %s: %s" % (str(d.line_num), str(row) ) )
        print( row[d.fieldnames[TheColumn]] )

output:

row 2: {'t1': '12', 't2': '23', 't3': '31'}
31

Upvotes: 1

Furqan Rahamath
Furqan Rahamath

Reputation: 2076

In short, convert the output of csv.DictReader to a list format and access the values with index.

Note: The value returned when you access by index will be an object with keys corresponding to the column names in the CSV file


Use Case:

I had a similar need. I only wanted to read a subset of rows, say lines 10-15 from a total of 100 lines.

A simple solution that worked was to convert it into list:

# Observe that I am converting the output of DictReader into a list format
lines = list(csv.DictReader(open('somefile.csv', 'r')))

# Once I have the list of objects, I can simple access it with range
for i in range(10, 15):
    line = lines[i]
    # If you want to read the value of a specific column
    print line['column_name']

Hope this helps.

Upvotes: 1

earl
earl

Reputation: 41825

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.)

Upvotes: 4

Andrea Spadaccini
Andrea Spadaccini

Reputation: 12651

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.

Upvotes: 10

Related Questions