Reputation: 2615
I got a question regarding Python in combination with CSV.
I want to check for specific id within in a specific column within a CSV file and find the results are connected to the input:
CSV:
What i want to do is that when a user put as an input: b0074, i want to return all the result: b00ph, b11ph, b22ph, b33ph
How can i do that within Python? Can anyone help me coding this? I got started with this:
with open('serials.csv') as csvfile:
csvreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
Upvotes: 0
Views: 5417
Reputation: 87124
Since you seem to want to use the CSV module, you can use a list comprehension to filter rows from the CSV file. Below, items in column 0 (row[0]) are compared to your key value (b0074). If they match column 1 is added to the result of the list comprehension.
import csv
key = 'b0074'
with open('serials.csv') as csvfile:
reader = csv.reader(csvfile, delimiter=' ', quotechar='|')
result = [row[1].strip() for row in reader if row[0].strip() == key]
>>> result
['b00ph', 'b11ph', 'b22ph', 'b33ph']
This is equivalent to this "normal" for loop:
import csv
key = 'b0074'
result = []
with open('serials.csv') as csvfile:
reader = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in reader:
if row[0].strip() == key:
result.append(row[1].strip())
>>> result
['b00ph', 'b11ph', 'b22ph', 'b33ph']
Upvotes: 2