Rotan075
Rotan075

Reputation: 2615

Get matching csv rows with Python

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:

CSV FILE


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

Answers (2)

mhawke
mhawke

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

EdChum
EdChum

Reputation: 394179

This can be easily achieved using pandas:

import pandas as pd
df = pd.read_csv(csvfile, sep=' ', quotechar='|')
df[df['Row1'] == 'b0074']

Will filter the dataframe and return all rows where 'Row1' has that value

Upvotes: 3

Related Questions