[Tutor] glob or filter help

Jacob S. keridee at jayco.net
Sat Jan 22 15:24:49 CET 2005


Filter can be replaced with IMHO the more readable list comprehensions.

I would try

def get_fles(exts,upd_dir):
    "return list of all the files matching any extensions in list exts"
    fle_list = []
    for each in exts:
        ext_ls = glob.glob("%s*.%s" % (upd_dir,each))
        fle_list.extend(ext_ls)
    return [x for x in fle_list if not islink(x)]

>I have the following code in my updates script (gets the five most recent
> updated files on my site)
>
> def get_fles(exts, upd_dir):
> '''return list of all the files matching any extensions in list exts'''
> fle_list = []
> for each in exts:
>  cmd = upd_dir + "*." + each
>  ext_ls = glob.glob(cmd)
>  fle_list = fle_list + ext_ls
> return filter(notlink, fle_list)
>
> I wanted to just get one list, of all the .htm and .exe files in my 
> upd_dir.
> I was trying to make a far more elegant solution that what's above, that
> could generate a list through a filter.  Is there a way to trim the code 
> down
> to something that does ONE sort through the directory and picks up the 
> .htm
> and .exe files? (note, it is not necessary for this to recurse through
> subdirectories in the upd_dir).  I have cmd defined above because calling
> "glob.glob(upd_dir + "*." + each) returned the error "cannot concatenate
> string and list objects" - is this the only way around that, or is there a
> better way?
>
> Also in the above code, "notlink" is just a function that returns True if
> "islink()" returns true....there has to be a better way to use this with
> filter(), how can i make filter use "if islink()!=true" as its condition?
>
> The script is working now, (I know, I know, if it ain't broke, don't fix
> it...) but I want to be a better programmer so more elegant solutions are
> accepted gratefully.
> -Jay
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



More information about the Tutor mailing list