[Tutor] how to extract number of files from directory

Michael Sparks zathras at thwackety.com
Thu Oct 13 01:58:20 CEST 2005


On Wednesday 12 October 2005 19:10, Marc Buehler wrote:
> i would like to extract the number of JPG files
> from the current directory and use that number

I've looked through the thread, and the following strikes me as simpler than 
the suggestions so far.

path = "." # Current directory, unix at least.
extns = ["jpg", "jpeg"]  # add in any others you like :-)
piccies = [ f for f in os.listdir(path) if f.split(".")[-1].lower() in extns ]
num_files = len(piccies)


What does this do?

os.listdir(path) -- gives you a list of files in that directory.
The condition:
     f.split(".")[-1].lower() in extns

Selects which filenames get put in the resulting list files.

This expression says "split the filename on dots '.' ", take the last thing
after the last dot, and make it lower. Finally check to see if that extension
is in the list of required extensions. 


I suppose if you prefer a more verbose version of the same thing:

path = "." # Current directory, unix at least.
extns = ["jpg", "jpeg"]  # add in any others you like :-)
piccies = []
for filename in os.listdir(path):
    extension = f.split(".")[-1]
    if extension.lower() in extns:
        piccies.append(filename)

num_files = len(piccies)

Regards,


Michael.


More information about the Tutor mailing list