user1681664
user1681664

Reputation: 1811

search column, return row from excel using python

I have a csv file with column A that has dates. I want to search the dates and return the corresponding row in array (VERY IMPT) format. How would I do that using python? Thank you.

excel file:

      A          B         C
1  12202014     403       302

2  12212014     312       674

3  12222014     193       310

input:

 Search csv file for 12212014

output:

[12212014,312,674]

attempt code:

date = '12212014'
with open('dates.csv', 'rt') as f:
     reader = csv.reader(f, delimiter=',')
     for row in reader:
          if date == row[0]: 
              print "found the date"

How do I return the row instead of just a print statement?

Upvotes: 1

Views: 2087

Answers (1)

alecxe
alecxe

Reputation: 473853

The basic idea is to create a dictionary/mapping date->line and get the value by the key:

import csv


data = {}
with open('test.csv', 'r') as f:
    reader = csv.reader(f)
    for line in reader:
        data[line[0]] = line

date_to_find = '12212014'
print data.get(date_to_find, 'Date not found')

prints:

['12212014', '312', '674']

This helps if you need the mapping afterwards to find the dates in it.

Another approach is to use generator expression to iterate over lines in a file until we find the date:

import csv


date_to_find = '12212014'
with open('test.csv', 'r') as f:
    print next((line for line in csv.reader(f) if line[0] == date_to_find), 
               'Date not found')

prints:

['12212014', '312', '674']

Hope that helps.

Upvotes: 2

Related Questions