Kaya Mehta Kaya Mehta - 21 days ago 8
Python Question

CSV Python -Spyder

I have a csv file of service price list where column a = name of service and column b = has price.

I need to make a function like def pricelist("servicepricelist.csv", "servicename") -- the first part states the file, the second part is asking to pull an element in the row of the file like "washing".

I need to somehow, make the washing or whatever service is entered match the csv file column a and then print the value from column b

the output has to be like:

49.95

Please help

Answer

Although I have not tested it, the following script should accomplish what you're looking for:

import csv


def price_list(path: str, service: str) -> str:
    value = None
    with open(path, newline='') as file:
        for name, price in csv.reader(file):
            if name == service:
                value = price
                break
    return value


if __name__ == '__main__':
    path = input('Path to csv: ')
    service = input('Service name: ')
    print(price_list(path, service))

All it does is import the standard library's csv module, open the file, iterate over its contents until it finds the service, and print out the corresponding price.

Comments