Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass a list of files to python open() method

I have a list of around 100 files form which I wanted to read and match one word. Here's the piece of code I wrote.

import re
y = 'C:\\prova.txt'
var1 = open(y, 'r')

for line in var1:
    if re.match('(.*)version(.*)', line):
        print line

var1.close() 

every time I try to pass a tuple to y I get this error:

TypeError: coercing to Unicode: need string or buffer, tuple found.

(I think that open() does not accept any tuple but only strings)

So I could I get it to work with a list of files?

Thank you in advance!!!!

like image 329
nassio Avatar asked Feb 05 '12 21:02

nassio


1 Answers

You are quite correct that open doesn't accept a tuple and needs a string. So you have to iterate over the file names one by one:

import re

for path in paths:
    with open(path) as f:
        for line in f:
            if re.match('(.*)version(.*)', line):
                print line

Here I use paths as the variable the hold the file names — it can be a tuple or a list or some other object that you can iterate over.

like image 82
Martin Geisler Avatar answered Sep 21 '22 22:09

Martin Geisler