[Tutor] Parsing several files

Luke Paireepinart rabidpoobear at gmail.com
Fri Aug 3 18:24:34 CEST 2007


Que Prime wrote:
>
> With the help of a tutor I was able to get the following code to work 
> the way I want, but I'd like for it to parse through several files in 
> one folder and create one output file.
>
> I'm thinking I need to add something like:
>
> def grab_files(files = []):
Default values are created when the function object is created, not on 
each call.
So given this:
def test(a = []):
   a.append(5)
   print a

it works how you'd think it would for a passed list:
 >>> x = []
 >>> test(x)
[5]
 >>> test(x)
[5, 5]
 >>> x
[5, 5]

But when you don't pass it a value,
 >>> test()
[5]
 >>> test()
[5, 5]
 >>> test()
[5, 5, 5]

As you can see, the default value isn't constant at [].

So if you do any operations on the default value, you should do 
something like this instead:
def test(a=None):
    if a == None:
        a = []

which will give you the behavior you probably expected.


Other than that, I would suggest doing it like this:
files = ['a','b','c'] #construct this however you want
outfile = open('output','w')
for filename in files:
    for line in open(filename):
        #do your regular pattern matching stuff here.
outfile.close()

You can put this in a function but if this is all your code does then I 
don't see the point of making a function,
it would just make the logic harder to follow.

I believe that the 'for line in open(filename):' will automatically read 
in the file and then close the file stream,
but you may want to check that it does close the file.
Code untested.
-Luke


More information about the Tutor mailing list