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?

2
  • possible duplicate of How to read a csv file with python Commented Apr 1, 2014 at 2: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 Commented Apr 1, 2014 at 2:25

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.