[Tutor] Re: glob or filter help
Jeff Shannon
jeff at ccvcorp.com
Tue Jan 25 02:16:14 CET 2005
Barnaby Scott wrote:
> For anyone who doesn't like lambda, how about
>
> import os
> def get_fles(exts, upd_dir):
> return [i for i in os.listdir(upd_dir) if i.split('.')[-1] in exts]
Better would be:
def get_fles(exts, upd_dir):
return [fname for fname in os.listdir(upd_dir) if \
os.path.splitext(fname)[-1] in exts \
and not fname.islink() ]
(This is split into three lines for readability, but can be entered as
a single line. Also, the '\' line-continuation is optional, as Python
will see that the list comp is still open and automatically continue
the line...)
Using os.path.splitext() to get the extension is safer and more
portable than simply splitting on '.', and it's self-documenting too!
(A month from now, you might need to think a moment to figure out
why you're splitting on '.', but the very name os.path.splitext()
tells you about the intent.)
Note that there's a slight difference here, in that exts will need to
list extensions *with* the leading '.' because splitext() will leave
it on --
>>> os.path.splitext('filename.txt')
('filename', '.txt')
>>>
I've also added a second clause to ensure that returned files are not
links, as per the rest of the O.P.'s spec.
Jeff Shannon
Technician/Programmer
Credit International
More information about the Tutor
mailing list