[Tutor] Lists of files

Bernard Lebel 3dbernard at gmail.com
Sat May 14 18:02:54 CEST 2005


Hi William,

First, check out the os and os.path modules. It has exactly what you
need to handle files and directories.
http://www.python.org/doc/2.4.1/lib/module-os.html
More specifically:
http://www.python.org/doc/2.4.1/lib/os-file-dir.html
http://www.python.org/doc/2.4.1/lib/module-os.path.html

import os

# Get list of files in directory
aFiles = os.listdir( <path to files> )

# Create empty list to store image files
aImgFiles = []

# Iterate list to collect image files
for sFile in aFiles:
     # Split extension to see if it is an image type
     # This returns a list of two elements, check the last one to get
the extension
     if os.path.splitext( sFile )[-1] == <animageextension>:
aImgFiles.append( sFile )



You could also do that more quickly with list comprehension:

aImgFiles = [ sFile for sFile in os.listdir( <pathtolistfiles> ) if
os.path.splitext( sFile )[-1] == <imageextension> ]



Cheers
Bernard



On 5/14/05, William O'Higgins <william.ohiggins at utoronto.ca> wrote:
> Here's the problem - I want a list (array) of the files in a directory,
> and then I want to iterate over the list testing for image-ness (with
> imghdr.what()) and put all the image filenames in a global list.
> 
> What I've tried is this:
> 
> files = glob.glob('*.*')
> 
> for file in files:
>     global pics
>     pics = []
>     if imghdr.what(file):
>         # so far so good - file is a list of files in the directory
>         pics.append(file)
>         # I this this is the problem - my list only has the last
>         # alphabetical entry in it
> 
> So there's two questions - is there a better way to create a list of
> files in a directory?  And, how do I populate my list to get all of the
> filenames.  I've also tried "pics + [file]", but that gave me an empty
> list.
> --
> 
> yours,
> 
> William
> 
> 
> BodyID:4269787.2.n.logpart (stored separately)
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
>


More information about the Tutor mailing list