newb question: file searching

Gabriel Genellina gagsl-py at yahoo.com.ar
Tue Aug 8 20:41:30 EDT 2006


At Tuesday 8/8/2006 21:11, jaysherby at gmail.com wrote:


>Here's my code:
>
>def getFileList():
>         import os
>         imageList = []
>         for dirpath, dirnames, filenames in os.walk(os.getcwd()):
>                 for filename in filenames:
>                         for dirname in dirnames:
>                                 if not dirname.startswith('.'):
>                                         if 
> filename.lower().endswith('.jpg') and not
>filename.startswith('.'):
> 
>imageList.append(os.path.join(dirpath, filename))
>         return imageList
>
>I've adapted it around all the much appreciated suggestions.  However,
>I'm running into two very peculiar logical errors.  First, I'm getting
>repeated entries.  That's no good.  One image, one entry in the list.

That's because of the double iteration. dirnames and filenames are 
two distinct, complementary, lists. (If a directory entry is a 
directory it goes into dirnames; if it's a file it goes into 
filenames). So you have to process them one after another.

>def getFileList():
>         import os
>         imageList = []
>         for dirpath, dirnames, filenames in os.walk(os.getcwd()):
>                 for filename in filenames:
>                         if filename.lower().endswith('.jpg') and 
> not filename.startswith('.'):
> 
>imageList.append(os.path.join(dirpath, filename))
>                 for i in reversed(range(len(dirnames))):
>                         if dirnames[i].startswith('.'): del dirnames[i]
>         return imageList

reversed() because you need to modify dirnames in-place, so it's 
better to process the list backwards.



Gabriel Genellina
Softlab SRL 


	
	
		
__________________________________________________
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas




More information about the Python-list mailing list