[Tutor] Example prog

Daniel Yoo dyoo@hkn.EECS.Berkeley.EDU
Sun, 27 Aug 2000 02:22:20 -0700 (PDT)


On Sun, 27 Aug 2000 amoreira@mercury.ubi.pt wrote:

> Hi!
> Your invocation of the script, where you say
> > C:\python>python pack1.py *.txt > stuff.txt
> tries to open all files with .txt extension in the current directory. If
> you don't have any, the script ends with that error message. Are you
> sure to have a .txt file in the working dir?
> I hope that that's it!

What's happening is that Windows systems do not substitute '*.txt' for the
files in the directory --- this behavior is in contrast to UNIX, and is
really unfortunate.  Every Windows program apparently has to do this
wildcard expansion manually.

Thankfully, Python provides a nice module that does a lot of the work that
UNIX does in doing wildcard substitutions.  It's called the 'glob' module,
so you should be able to do something like this:


### globfileargs.py
import glob
def getGlobbedFilenames(args):
    results = []
    for a in args:
        l = glob.glob(a)
        if len(l) > 0:
            results = results + l
    return results


import sys
if __name__ == '__main__':
    print "Here's sys.argv[1:]:", sys.argv[1:]
    args = getGlobbedFilenames(sys.argv[1:])
    print "And here is an expanded list of the files we can match:"
    print args
###

For example:

###
[dyoo@einfall dyoo]$ python globfiles.py '*.py'
Here's sys.argv[1:]: ['*.py']
And here is an expanded list of the files we can match:
['globfiles.py', 'graph.py']
###


Hopefully, this should fix things for you.