How to search for value in a sequence in Python?

3985 views python
-3

I am very new to coding so please bear with me. Basically I am writing a program that will ask for either a last name or id number, then search a .csv file for the word and return the entire column to which it belongs. Below is what I have written if the user opts to search by the id.

method = input("Search by invoice id (id) or customer last name (lname)?: ")
    data = "data.csv"
    dataFile = open(data, "r")
    dataRows = dataFile.readlines()

if method == "id":
    term = input("Enter the id: ")
    for line in dataRows:
        row = line.strip()
        newRow = row.split('\n')
        if term == newRow[0]:
            print(newRow)
        else:
            print("No matches found.")

This is the csv file: Here is a photo of the csv file.

This is how it prints out after readlines():

['invoice id,first name,last name,part number,quantity,total']
['111,Jim,Morrison,27,1,50.25']
['222,Ray,Manzarek,25,2,64.46']
['333,John,Densmore,16,4,34.34']
['333,Robby,Krieger,32,2,34.34']
['555,Jim,Morrison,12,4,43.34']
['333,Jim,Morrison,35,2,34.76']
['888,John,Densmore,63,2,34.76']
['111,Robby,Krieger,21,1,64.45']
['458,Freddie,Mercury,32,4,45.23']
['111,Freddie,Mercury,21,1,46.2']
['234,Allie,McGuire,43,3,64.45']
['675,Allie,McGuire,32,4,45.23']
['359,Freddie,Mercury,423,2,34.34']

Since invoice ID is the first column, I thought it would be found by using if term ==newRow[0], but that's not working. Any tips? Thanks so much.

answered question

you should use the csv module when handling CSVs. all of the row splitting and other operations are taken care of for you

@RoadRunner i added it, thank you!

If the data is comma separated, shouldn't it be: newRow = row.split(',')?

@aydow unfortunately our teacher hasn't taught us that, but good idea!

1 Answer

1

If you don't want to use the csv module for this problem, then you should split your string on ",", not on "\n":

newRow = row.split(",")

This way, the first element of newRow will be the invoice id.

posted this

Have an answer?

JD

Please login first before posting an answer.