[Tutor] bash find equivalent in Python
R. Alan Monroe
R. Alan Monroe" <amonroe@columbus.rr.com
Fri Jul 11 12:33:08 2003
> While this seems to work, it also seems wrong to have to guess how many
> levels deep my directory structure is and copy, paste and indent the code
> accordingly. Is there a recursive find utility in Python similar to bash
> find ? For example:
You could probably convert your existing program into a recursive one.
Here's one I wrote a few months ago that might give you some ideas.
class node:
def __init__(self,name):
self.size=0
self.name=name
self.files=[]
self.dirs=[]
#----------
import os
startdir="c:\\winnt"
def walker(startdir):
print "BEGIN", startdir, "\r",
os.chdir(startdir)
here=node(startdir)
#print here
listing = os.listdir(startdir)
#print listing
for x in listing:
#print " DECIDE ", x,
#print x
#print os.path.abspath(x)
if os.path.isfile(x):
#print x, "is a file"
y=os.path.getsize(x)
here.files.append((x,y))
here.size += y
elif os.path.isdir(x):
#print x, "is a dir"
#print os.path.abspath(x)
recurse = walker(os.path.abspath(x))
here.dirs.append(recurse)
here.size += recurse.size
os.chdir(startdir)
else:
#print x, "is neither"
pass
#print "DONE ", startdir
return here
def display(here,level):
for x in range(level):
print " ",
print level, here.name, ":", here.size,
#y=0
for x in here.dirs:
if here.size>0:
#y += float(x.size)/float(here.size)
print float(x.size)/float(here.size)
else:
print "0.0000000000"
display(x,level+1)
#print y
root=walker(startdir)
print root.size
print "\n\n\n\n"
display(root,0)