1

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?

user1681664
  • 1,771
  • 8
  • 28
  • 53
  • possible duplicate of [How to read a csv file with python](http://stackoverflow.com/questions/1593318/how-to-read-a-csv-file-with-python) – Paulo Scardine Apr 01 '14 at 02:17
  • @PauloScardine Hello. I tried looking at that, but it does not show me how to search within a specific column and return the whole row in array format – user1681664 Apr 01 '14 at 02:25

1 Answers1

2

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.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195