Allie M
Allie M

Reputation: 61

How to search for value in a sequence in Python?

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.

Upvotes: 3

Views: 509

Answers (2)

Abhinav Sood
Abhinav Sood

Reputation: 789

The simplest way to do this is using the csv module:

method = input('Search by invoice id (id) or customer last name (lname)?: ')
term = input('Enter the term: ')

found_row = None     # To store the row if a match is found

with open('data.csv', newline='') as csvfile:
    reader = csv.DictReader(csvfile)

    for row in reader:
        # Compare term with Invoice ID if chosen method is ID
        # else compare with Last Name
        if term == (row['invoice id'] if method == 'id' else row['last name']):
            found_row = row

if found_row:
    print(row)
else:
    print('No match found')

If you're allowing the user to search by ID or last name only, it's possible to simplify your input even further by asking them to enter 1 for ID and 2 for Last Name. This approach is inflexible but the advantage is that users are less likely to enter the method in wrong case. For example, you're comparing method == 'id' but the user might enter Id or ID. Might make your life a bit simpler.

Upvotes: 1

Joel
Joel

Reputation: 1574

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.

Upvotes: 0

Related Questions