我编写了一段代码,读取作为输入给出的产品并给出产品价格的输出
data.csv 文件
1, 4.00, teddy_bear
1, 8.00, baby_powder
2, 5.00, teddy_bear
2, 6.50, baby_powder
3, 4.00, pampers_diapers
3, 8.00, johnson_wipes
4, 5.00, johnson_wipes
4, 2.50, cotton_buds
5, 4.00, bath_towel
5, 8.00, scissor
6, 5.00, scissor
6, 6.00, bath_towel, cotton_balls, powder_puff
Python代码
import csv
with open('data.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
usrid = []
price = []
product = []
for row in readCSV:
usrid.append(row[0])
price.append(row[1])
product.append(row[2])
askProduct = raw_input('What Product do you wish to know the price of?:')
abc = product.index(askProduct)
thePrice = price[abc]
print ('the price of product',askProduct, 'is', thePrice)
生成错误
Traceback (most recent call last):
File "C:/Users/Desktop/program.py", line 15, in <module>
abc = product.index(askProduct)
ValueError: 'teddy_bear' is not in list
需要以下输出
Program Input
program data.csv teddy_bear baby_powder
Expected Output
=> 2(userid), 11.5(addition of two products)
最佳答案
您的 CSV 中有多余的空间,因此您的产品实际上是“teddy_bear”
。 Python 的 csv.reader()
允许您使用 skipinitialspace
参数告诉它忽略分隔符周围的额外空格:
csv.reader(csvfile, delimiter=',', skipinitialspace=True)
关于python - 读取 CSV 中的特定数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45064708/