How can I find multiple strings in a csv file

Viewed 445

so I am trying to learn python and have a csv file like this

 1  product_id  product_name    price
 2  1001    cake    15
 3  1002    sprite  30
 4  1003    coffee  50
 5  1004    ice cream   30
 6  1005    banana  10

my program is

import csv

productid=input("Enter the product ID: ")
quantity=int(input("Enter the quantity: "))
csv_file=csv.reader(open("shoppinglist.csv", "r"),delimiter=",")

for row in csv_file:
    if productid==row[0]:
        product_id=row[0]
        product_name=row[1]
        product_price=row[2]
        print("\nProduct ID: {}".format(row[0]))
        print("Product Name: {}".format(row[1]))
        print("Product Price: {}".format(row[2]))

total=quantity*(int(product_price))
print("\nThe Total Amount Payable is: {}".format(total))

I can enter one productid at a time and get the output but i am looking for a way so that i can enter multiple productid's ad they get searched in the csv file and then the total is calculated and all the product details output.

PS: I have tried to explain my problem as best as i can but if i have made any mistake please be kind to point it out to me

my output is

Enter the product ID: 1001 Enter the quantity: 5

Product ID: 1001 Product Name: cake Product Price: 15

The Total Amount Payable is: 75

i just do not want to print the product but to search for its id in the csv file and if it exits ask the user to input the quantity for every productid entered and then print the details of the products along with the total amount.

3 Answers

You can just parse your input to be the way you want. For example,

def product(id): # given product id, returns price, 0 if item does not exist
    # your code goes here

id = input("Enter your product ids separated by spaces: ") # For e.g. 2 3 1
id = id.split(" ")

total = 0
for i in id:
    price = product(id)
    if price != 0:
        quantity = print("Enter quantity of " + str(id) + ": ")
        total += quantity*price

print("The total price is: " + price)

This code parses the ids so they are in an array. It then goes through each id in the array and performs your code.

You should really look into pandas, it's going to make all these kinds of operations much simpler.

enter image description here

You Need a Loop to look around to your product each time you offered a product Id I Hope You Understand the following code.

    # Author Name : Sandip Sadhukhan

    import csv


    def findProduct(productId):
        csv_file = csv.reader(open('shoppinglist.csv', 'r'), delimiter=',')
        productPrice = 0
        productName = ''
        isFound = False
        for row in csv_file:
            if productId == row[0]:
                productName = row[1]
                productPrice = row[2]
                isFound = True
                break
        result = {
            'isFound': isFound,
            'productName': productName,
            'productPrice': productPrice,
            'productId': productId
        }
        return result


    total = 0
    printList = []
    while(True):
        productid = input("Enter a product Id: ")
        result = findProduct(productid)
        if not(result['isFound']):
            print("Product is not found...")
            continue

        quantity = int(input("Enter the quantity: "))
        if(quantity <= 0):
            print("Please select atleast 1 quantity.")
            continue
        total += quantity * (int(result['productPrice']))
        temp = [result['productName'], quantity, result['productPrice']]
        printList.append(temp)
        addMore = input("Add more Items? (Y/N) : ")
        if(addMore.lower() == 'n'):
            break

    print("\nBill\n====\n\n[Product Name] [Product Price] [Quantity]")
    for item in printList:
        print("{}  {}  {}".format(item[0], item[2], item[1]))
    print("The total Amount payable is : {}".format(total))
Related