How to read a specific value form a row in CSV file?

I was trying to write a function that read a CSV file that looks like this.

flowers.csv

petunia,5.95
alyssum,3.95
begonia,5.95
sunflower,5.95
coelius,4.95

I have tried this code for my function.

def read_csv(csv_pricefile):
    import csv 
    f = open(csv_pricefile)
    li = []
    for row in csv.reader(f):
        li.append(row)
    f.close()
    print(li)

read_csv("flower.csv")

when I call my function it gives the following output.

[['petunia', '5.95'], ['alyssum', '3.95'], ['begonia', '5.95'], ['sunflower', '5.95'], ['coelius', '4.95']]

But I don’t know how to write a function that will take two parameters for example,

read_csv("flowers.csv","alyssum")

If I call the function, it should give me the following output.

3.95

Answer

Use pandas library for read csv, this will make a dataframe object

import pandas as pd
df = pd.read_csv('flowers.csv')
df.columns =['flower','price']

Then if you want to know price of any flower

df = df.set_index(['flower'])
f = 'alyssum'
print("{} costs {}".format(f,df.loc[f].price))

Leave a Reply

Your email address will not be published. Required fields are marked *