0

I have hundreds of CSV files and I'm trying to write a Python script that will parse through all of them and print out rows that have matching string(s). I'll be happy if we can get this to work using one string (and not a list of strings). Using Python 2.7.5. I've figured out so far:

The csv module in Python will print the row with the matching string in a particular column (the eighth column from the left):

import csv
reader = csv.reader(open('2015-08-25.csv'))
for row in reader:
    col8 = str(row[8])
    if col8 == '36862210':
        print row  

So the above works for one .csv file. Now I need to parse hundreds of .csv files with glob. The glob module will print out all the file names with this code:

import glob
for name in glob.glob('20??-??-??.csv'):
    print name

I tried putting the two together into one script but the error message reads:

File "test7.py", line 6, in reader = csv.reader(open(csvfiles)) TypeError: coercing to Unicode: need string or buffer, list found

import csv
import glob

csvfiles = glob.glob('20??-??-??.csv')
for filename in csvfiles:
    reader = csv.reader(open(csvfiles))
    for row in reader:
        col8 = str(row[8])
        if col8 == '36862210':
            print row

1 Answer 1

0

You are trying to open a List - csvfiles is the list you are iterating on.

Use this instead, because open() expects a filename:

reader = csv.reader(open(filename))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it works! However it doesn't like the two empty rows at the top of each of my .csv files. I've started another post at stackoverflow.com/questions/32216221/…

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.