[英]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.我试图编写一个 function 来读取一个看起来像这样的 CSV 文件。
flowers.csv花。csv
petunia,5.95
alyssum,3.95
begonia,5.95
sunflower,5.95
coelius,4.95
I have tried this code for my function.我已经为我的 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.当我打电话给我的 function 时,它会给出以下 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,但我不知道如何编写一个 function ,例如,它将采用两个参数,
read_csv("flowers.csv","alyssum")
If I call the function, it should give me the following output.如果我调用 function,它应该给我以下 output。
3.95
Use pandas library for read csv, this will make a dataframe object使用 pandas 库读取 csv,这将生成 dataframe ZA8CFDE6331BD59EB266AC96F8911ZC4
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))
Here is my solution I just tried这是我刚刚尝试过的解决方案
def read_csv(csv_pricefile,flower):
import csv
f = open(csv_pricefile)
my_dic = {}
for row in csv.reader(f):
myData = {row[0]:row[1]}
my_dic.update(myData)
f.close()
print(my_dic[flower])
read_csv("flower.csv","alyssum")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.