简体   繁体   中英

Searching CSV file and if it's not in the file

I have a CSV file filled with ticket information. I created a small script to input ticket numbers separated by spaces into a list which searches the CSV file for each ticket in the list, and if it finds the ticket, it outputs info on that row.

My problem is if I search for a ticket not in the CSV file, it just skips past it and moves on, but I would like it to tell me that that ticket is not in the file. From what I can tell, it's searching the CSV file by row or line. If I try an else statement, it will start printing out every line in the CSV file, if that ticket's not in the row.

I need to be able to input multiple ticket numbers and have python search each one individually. If it finds the ticket in column 1, then print information from that row and if it doesn't find the ticket in any rows column 1, then print out that ticket followed by "is not in the file".

import csv

file = csv.reader(open('Path To CSV file', "rb"), delimiter=",")
newticket = raw_input('Enter Ticket Numbers:').split()

for line in file:
    for tickets in newticket:
        if tickets == line[1]:
            print(tickets, line[36], line[37])

If your CSV file isn't enormous, I suggest reading the whole thing, extracting the data you want into a dictionary, with the ticket number as the key. Searching a dict is very fast.

I've modified your file opening code to use the with statement, which fails gracefully if there's a problem reading the file. BTW, there's no need to specify the comma as the CSV delimiter, since that the default delimiter.

import csv

with open('Path To CSV file', "rb") as f:
    data = {line[1]: (line[36], line[37]) for line in csv.reader(f)}

newtickets = raw_input('Enter Ticket Numbers:').split()

for ticket in newtickets:
    line = data.get(ticket)
    if line:
        print(ticket, line)
    else:
        print(ticket, "not found")

The dict.get method returns None if the key isn't in the dict, although you can specify another default return value if you want. So we could re-write that part like this:

for ticket in newtickets:
    line = data.get(ticket, "not found")
    print(ticket, line)

Alternatively, we could use the in operator:

for ticket in newtickets:
    if ticket in data:
        print(ticket, data[ticket])
    else:
        print(ticket, "not found")

All 3 versions have roughly the same efficiency, choose whichever you feel is the most readable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM