1 #!/usr/bin/env python
   2 import os,fnmatch,sys
   3 
   4 # Usage:
   5 # ./walkdir.py directory extension
   6 
   7 dir,ext=sys.argv[1],sys.argv[2]
   8 fileList=[]
   9 for root, dirs, files in os.walk(dir):
  10     f=fnmatch.filter(files,'*.'+ext)
  11     if type(f)==type([]):
  12         for fi in f:
  13             fName=root+os.path.sep+fi
  14             fSize=os.path.getsize(fName)
  15             fileList.append([fSize,fName])
  16 fileList.sort()
  17 fileList.reverse()

Alternative version with a class

   1 #!/usr/bin/env python
   2 import os,fnmatch,sys
   3 
   4 # Usage:
   5 # ./walkdir.py directory extension  
   6 
   7 #Class FileWalker
   8 #Searches for files and is able to sort and print a filelist 
   9 
  10 class FileWalker(object): 
  11  def __init__(self,Dir, Ext):
  12          self.__fileList=[]
  13          self.__dir=Dir
  14          self.__ext=Ext
  15          self.__initFileList()
  16  def __initFileList(self): 
  17         for root, dirs, files in os.walk(self.__dir):
  18                 f=fnmatch.filter(files,'*.'+self.__ext)
  19                 if type(f)==type([]):
  20                         for fi in f:
  21                                 fName=root+os.path.sep+fi
  22                                 fSize=os.path.getsize(fName)
  23                                 self.__fileList.append([fSize,fName])
  24  def getFileList(self):
  25         return self.__fileList
  26  def sortFileList(self,descending=False):
  27          self.__fileList.sort()
  28          print descending
  29          if descending:
  30                 self.__fileList.reverse()
  31  def printFileList(self,Cnt=None):
  32          if not Cnt is None :
  33                  for i in range(Cnt):
  34                         item=self.__fileList[i]
  35                         entry = str(item[0])
  36                         entry =entry+' '+item[1]
  37                         print entry
  38          else:
  39                 for item in self.__fileList:
  40                         entry = str(item[0])
  41                         entry =entry+' '+item[1]
  42                         print entry
  43 
  44         
  45         
  46 
  47 # Main 
  48 fw = FileWalker(sys.argv[1],sys.argv[2])
  49 fw.sortFileList(True)
  50 fw.printFileList()

LehreWiki: Python/Exercise3/Group1 (last edited 2009-01-19 14:59:54 by FabianGroße)