count files in a directory

James Stroud jstroud at mbi.ucla.edu
Sat May 21 00:25:03 EDT 2005


Sorry, I've never used os.walk and didn't realize that it is a generator.

This will work for your purposes (and seems pretty fast compared to the 
alternative):

file_count = len(os.walk(valid_path).next()[2])


The alternative is:


import os
import os.path

file_count = len([f for f in os.listdir('.') if os.path.isfile(f)])


On Friday 20 May 2005 08:08 pm, rbt wrote:
> James Stroud wrote:
> > def count_em(valid_path):
> >   root, dirs, files = os.walk(valid_path)
> >   return len(files)
>
> Here's another Tback:
>  >>> Traceback (most recent call last):
>
>    File "C:\Program
> Files\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py",
> line 310, in RunScript
>      exec codeObject in __main__.__dict__
>    File "C:\Documents and Settings\rbt\Desktop\newa\replicate.py", line 62,
> in ? A = count_em(X)
>    File "C:\Documents and Settings\rbt\Desktop\newa\replicate.py", line 56,
> in count_em root, dirs, files = os.walk(valid_path)
> ValueError: need more than 2 values to unpack

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/



More information about the Python-list mailing list