[Tutor] RE: Filtering text files

Garry Knight garryknight at gmx.net
Thu Apr 15 15:21:36 EDT 2004


In message <9A4B2157EFDBE546BECD68C62AC3B1C81738F0D2 at es05snlnt.sandia.gov>,
Kooser, Ara S wrote:

>     def filterFile(lmps,out):
>         inp = open("lmps.txt", "r")
>         outp = open("out.txt", "w")
...
>     filterFile("lmps.txt","out.txt")

Alan explained what was going wrong with your code. I just thought I'd point
out something else: you're calling filterFile with 2 arguments, "lmps.txt"
and "out.txt", but those arguments are not being used in the filterFile
function. You've declared that filterFile takes two parameters, lmps and
out, but you don't actually use them in the function; instead, you've
directly embedded the filenames in the body of the function.

This is OK if you don't ever intend to call filterFile with different
filenames, but it's redundant practice to declare parameters and then not
use them. It's more usual to do this kind of thing:

     def filterFile(lmps,out):
         inp = open(lmps, "r")
         outp = open(out, "w")
...
     filterFile("lmps.txt","out.txt")

What's happening here is that you're calling filterFile with the arguments
"lmps.txt" and "out.txt". Within the function, the parameter lmps 'stands
for' the argument "lmps.txt" and so the open() call works just as you want
it to. Likewise, the parameter out 'stands for' the argument "out.txt" and
so the second open() call works, too.

So you don't actually need to use names like 'lmps' and 'out' for the
filterFile function's parameters. It might make more sense to call them
something like 'infname' and 'outfname':

     def filterFile(infname,outfname):
         inp = open(infname, "r")
         outp = open(outfname, "w")
...
     filterFile("lmps.txt","out.txt")

Do you understand what's going on here? The string "lmps.txt" is being
passed to the filterFile function, which receives it into the parameter
'infname'. The open() call uses it to open the correct file. A similar
thing happens with the string "out.txt" and the parameter 'outfname'. You
could later call the function with:
        filterFile("other.txt", "thisone.txt")
and the file "other.txt" would be read and the results written to the file
"thisone.txt".

What you're seeing in action is the substitution of arguments to a function
into the parameters of a function and it's one of the main reasons for
having functions in the first place: so that the same piece of code can be
reused over and over again with different arguments.

If you're still not sure about all this, you might want to re-read one or
more of the tutorials that deal with functions. And by all means, ask more
questions on this list.

-- 
Garry Knight
garryknight at gmx.net  ICQ 126351135
Linux registered user 182025




More information about the Tutor mailing list