python - 读取 CSV 中的特定数据

标签 python python-2.7 csv

我编写了一段代码,读取作为输入给出的产品并给出产品价格的输出

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/

相关文章:

Python Flask SQLalchemy 外键未保存在数据库中 - 一对多

javascript - 如何将数据从表单传递到路由器

bash - 在 bash 中连接文件时处理空文件

python - Pytorch .to ('cuda' ) 或 .cuda() 不起作用并且卡住了

python - 定义类 : How to inheriting from object class

python - 使 __call__ 成为基类中可用于所有派生类的特定接口(interface)

python - 基于规则的 ngram 映射

python - 带有 2 行标题并导出到 csv 的 pandas 数据框

python asyncio socket在每个第一个连接上都低速

python - 创建一个新列,该列是每个用户从第一个订单日期算起的周数?