[Tutor] ok, I want to read a dir.

Michael P. Reilly arcege@speakeasy.net
Thu, 27 Dec 2001 09:38:33 -0500

On Wed, Dec 26, 2001 at 10:58:33PM -0500, Kirk Bailey wrote:
> Say, looking this over, FILTER looks like a good candidate for this job.
> files=os.listdir('./lists/')            # this creates a raw dir listing
> filelist=[]                             # create an empty list
> fnmatch.filter(filelist, "*.info")      # return the subset of list
> which match!
> this is not right, but close. What is the right way to use fnmatch and
> filter?

filelist = fnmatch.filter(os.listdir('./lists'), "*.info")

or going back to the glob module:

filelist = glob.glob1('./lists', "*.info")

> This is the error I get:
> ns# ./TLpost.py
> Traceback (innermost last):
>   File "./TLpost.py", line 189, in ?
>     listname = sys.argv[1]
> IndexError: list index out of range
> ns# 
> And that puzzles hell out of me.

This is a different error. The sys.argv is a list with the words from
the command line.

$ cat showargs.py
import sys
print sys.argv
$ python showargs.py
$ python showargs.py hi there
['showargs.py', 'hi', 'there']
$ python showargs.py "hi there"
['showargs.py', 'hi there']

Your command has only the program name and no other arguments.
So sys.argv[1] would be out of bounds in the list (there is only one
element).  You might want to put a try-except around the statement.

  listname = sys.argv[1]
except IndexError:
  raise SystemExit("list name argument required")

And if you ever want to add command-line options, you might want to look
into the getopt module.