Dommol
Dommol

Reputation: 191

Python CSV reader print out specific field

I'm looking for the most pythonic way to read a specific value from a string of csv values.

Here is an example:

I have the string 12022,0.0000,0.0000,70 and need to store each value to a variable. So

id = 12022
val = 0.0000
val2 = 0.0000
rsn = 70

Is there a way in python to grab the value from the csv reader from a specific location i.e.:

reader = csv.reader(value.string.split(","))
id = reader[0]
val = reader[1]

Upvotes: 1

Views: 2303

Answers (3)

Daniel
Daniel

Reputation: 2459

There is; it's very straightforward.

Return a Value from a Specific Row/Column of a csv:

import csv

f = open("example.csv")
csv_f = list(csv.reader(f))

#returns the value in the second row, second column of your file
print csv_f[1][1]

Upvotes: 1

Thomas Lee
Thomas Lee

Reputation: 1372

Do you mean something like this?

id, val, val2, rsn = reader

It will unpack values in the reader into corresponding variables.

For example:

for row in csv.reader(open('data.csv')):
    id, val, val2, rsn = row
    # do something...

Upvotes: 2

timakro
timakro

Reputation: 1841

I guess you are using a file, which makes the most sence for csv. Using the filednames makes it really clear.

import csv
with open("file.csv") as csvfile:
    reader = csv.DictReader(csvfile, fieldnames=("id", "val", "val2", "rsn"))
    for row in reader:
        id = float(row["id"])
        print id

You could also use this, which would be okay for the small example with only one line.

id, val, val2, rsn = [float(n) for n in string.split(",")]

Upvotes: 0

Related Questions