Just want to walk a single directory

Tim Peters tim.peters at gmail.com
Sat Jan 14 18:01:23 EST 2006

[stevebnospam428 at hotmail.com]
> I have a super-simple need to just walk the files in a single directory.
> I thought this would do it, but "permanentFilelist" ends up containing
> all folders in all subdirectories.

All folders everywhere, or all file (not directory) names in the top
two levels?  It looks like the latter to me.

> Could someone spot the problem? I've scoured some threads using XNews reg
> expressions involving os.walk, but couldn't extrapolate the answer for my
> need.
> ===============================================
> thebasedir = "E:\\temp"
> permanentFilelist= []
> for thepath,thedirnames,thefilenames in os.walk(thebasedir):
>         if thepath != thebasedir:

You wanted == instead of != there.  Think about it ;-)

>                 thedirnames[:] = []
>         for names in thefilenames:
>                 permanentFilelist.append(names)

A simpler way (assuming I understand what you're after) is:

    thebasedir = "C:\\tmpold"
    for dummy, dummy, permanentFilelist in os.walk(thebasedir):

or the possibly more cryptic equivalent:

    thebasedir = "C:\\tmpold"
    permanentFilelist = os.walk(thebasedir).next()[-1]

or the wordier but transparent:

    thebasedir = "C:\\tmpold"
    permanentFilelist = [fn for fn in os.listdir(thebasedir)
                         if os.path.isfile(os.path.join(thebasedir, fn))]

More information about the Python-list mailing list