Yash Shah
Yash Shah

Reputation: 125

read specific data in CSV

I have written a code that reads the product given as an input and gives the output of the price of the product

data.csv file

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 code

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)

error generated

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

following output is needed

Program Input
program data.csv teddy_bear baby_powder

Expected Output

=> 2(userid), 11.5(addition of two products)

Upvotes: 2

Views: 1260

Answers (5)

efirvida
efirvida

Reputation: 4855

your code not only fails but the space, you also miss the last products comma separated. here is my suggestion

import csv

with open('data.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    usrid = []
    price = []
    product = []
    for row in readCSV:
        # tmp_products =  row[2].split().strip()
        for the_product in row[2::]:
            usrid.append(row[0])
            price.append(row[1])
            product.append(the_product.strip())

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)

And also you have same product with different price so the code may be like:

import csv

with open('data.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    usrid = []
    price = []
    product = []
    for row in readCSV:
        # tmp_products =  row[2].split().strip()
        for the_product in row[2::]:
            usrid.append(row[0].strip())
            price.append(row[1].strip())
            product.append(the_product.strip())

askProduct = raw_input('What Product do you wish to know the price of?: ')
abc = [i for i, x in enumerate(product) if x == askProduct]
thePrice = [ price[p] for p in abc]
print ('the price of product',askProduct, 'is', thePrice)

UPDATE

import csv

with open('data.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',', skipinitialspace=True)
    usrid = []
    price = []
    product = []
    for row in readCSV:
        for the_product in row[2::]:
            usrid.append(row[0])
            price.append(float(row[1]))
            product.append(the_product)

askProduct = raw_input('What Product do you wish to know the price of?: ')
abc = [i for i, x in enumerate(product) if x == askProduct]
thePrice = [price[p] for p in abc]
print ('the price of product',askProduct, 'is', min(thePrice))

Upvotes: 0

Mikael Ferland
Mikael Ferland

Reputation: 1

It's not perfect but it's working like you want.

import argparse
import csv

parser = argparse.ArgumentParser(description='What Product do you wish to know the price of?:')

parser.add_argument('csvFileName',metavar='f', type=str,
                   help='a csv file with , as delimiter')
parser.add_argument('item1',  type=str,
                   help='a first item')
parser.add_argument('item2',  type=str,
                   help='a second item')

args = parser.parse_args()

with open(args.csvFileName) as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')

    listOfProduct = []
    #Fetch csv
    for row in readCSV:
        item = (row[0].replace(' ', ''), row[1].replace(' ', ''), row[2].replace(' ', ''))  
        listOfProduct.append(item)

    #Find all user corresponding with product
    item1found = [product for product in listOfProduct if product[2] == args.item1]
    item2found = [product for product in listOfProduct if product[2] == args.item2]

    allUserProducts = []    
    #Find item1 that corresponding with item2
    for item in item1found:
        (userId, price, product) = item
        otherUserProducts = [product for product in item2found if product[0] == userId]
        otherUserProducts.append(item)

        allUserProducts.append(otherUserProducts)

    for userProducts in allUserProducts:
        totalPrice = 0

        for product in userProducts:
            (userId, price, product) = product
            totalPrice += float(price)

        print '(' + str(userId) + ')','(' + str(totalPrice)+ ')'

Upvotes: 0

zwer
zwer

Reputation: 25789

You have an extra space in your CSV, so your product is actually " teddy_bear". Python's csv.reader() allows you to tell it to ignore extra spaces around separators with the skipinitialspace argument:

csv.reader(csvfile, delimiter=',', skipinitialspace=True)

Upvotes: 4

APorter1031
APorter1031

Reputation: 2256

You need to get rid of the space before each cell in the row. Since the delimiter is '," and your data file has a space after each ","

import csv

with open('data.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    usrid = []
    price = []
    product = []
    for row in readCSV:
        usrid.append(row[0].strip())
        price.append(row[1].strip())
        product.append(row[2].strip())

    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)

Upvotes: 1

Gautham Velchuru
Gautham Velchuru

Reputation: 75

I would check exactly how your lists are composed, it is very possible that your product array is something like [' teddy_bear', ' baby_powder'], etc due to the way the CSV is constructed. One way to solve this could be to try

usrid.append(row[0].strip())

which should strip whitespace when adding

Upvotes: 0

Related Questions