newb question: file searching

Justin Azoff justin.azoff at gmail.com
Tue Aug 8 22:12:28 EDT 2006


jaysherby at gmail.com wrote:
> I do appreciate the advice, but I've got a 12 line function that does
> all of that.  And it works!  I just wish I understood a particular line
> of it.

You miss the point.  The functions I posted, up until get_files_by_ext
which is the equivalent of your getFileList, total 17 actual lines.
The 5 extra lines give 3 extra features.  Maybe in a while when you
need to do a similar file search you will realize why my way is better.

[snip]
> The line I don't understand is:
> reversed(range(len(dirnames)))

This is why I wrote and documented a separate remove_hidden function,
it can be tricky.  If you broke it up into multiple lines, and added
print statements it would be clear what it does.

l  = len(dirnames) # l is the number of elements in dirnames, e.g. 6
r  = range(l) # r contains the numbers 0,1,2,3,4,5
rv = reversed(r) # rv contains the numbers 5,4,3,2,1,0

The problem arises from how to remove elements in a list as you are
going through it. If you delete element 0, element 1 then becomes
element 0, and funny things happen.  That particular solution is
relatively simple, it just deletes elements from the end instead.  That
complicated expression arises because python doesn't have "normal" for
loops.  The version of remove_hidden I wrote is simpler, but relies on
the even more obscure lst[:] construct for re-assigning a list.  Both
of them accomplish the same thing though, so if you wanted, you should
be able to replace those 3 lines with just

    dirnames[:] = [d for d in dirnames if not d.startswith('.')]


-- 
- Justin




More information about the Python-list mailing list