count file

Mike C. Fletcher mcfletch at rogers.com
Fri May 31 13:21:55 EDT 2002


I don't think this is safe on systems where a symbolic link can give you 
an infinite loop, will let you figure out how to avoid that.  (Hint: 
either avoid tracking through symlinks or keep a dictionary of visited 
directories and pass it to each iteration).  Oh, this is Python 2.2 
code, won't work with 1.5.2.

Enjoy,
Mike

import os
def countdir( dirname ):
     base = os.listdir( dirname )
     base = [
         f
         for f in base
         if os.path.isfile( os.path.join(dirname,f) )
     ]
     return len(base)
def rcountdir( dirname ):
     base = os.listdir( dirname )
     fcount = len([
         f
         for f in base
         if os.path.isfile( os.path.join(dirname,f) )
     ])
     for subdir in [
         d
         for d in base
         if os.path.isdir( os.path.join( dirname, d))
     ]:
         fcount = fcount + rcountdir( os.path.join( dirname, subdir) )
     return fcount


if __name__ == "__main__":
     print countdir( "c:\\" )
     print countdir( "d:\\" )
     print rcountdir( "c:\\bin" )

And finally, you might want to look at the os.path.walk function.  There 
is also an iterator-based examples hanging around that you could adapt...

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/105873

Enjoy,
Mike

Gold Fish wrote:
> Gerhard Häring wrote:
> 
> 
>>In article <53HJ8.7782$fG3.277261 at news2.ulv.nextra.no>, Erlend J. Leiknes
>>wrote:
>>
>>>import os.path
>>>path = "/"
>>>items = os.path.listdir(path)
>>>myfiles = []
>>>for i in range(len(items):
>>>    if os.path.isfile(path + items[i]):
>>>        myfiles.append(path + items[i])
>>
>> 
>>It's better to use os.path.join to join path elements, as this will work
>>on any platform. There's no cross-platform way to get the root directory,
>>though. On some platforms (Windows, for example), there might not even be
>>a single root directory.
>>
>>Gerhard
> 
> How about the directory have another subdirectory, i tried your way but it 
> show an error when i got subdirectory in the original directory


-- 
_______________________________________
   Mike C. Fletcher
   http://members.rogers.com/mcfletch/







More information about the Python-list mailing list