用Python生成目录树

http://www.iteye.com/topic/494257

 

 

  1. # encoding: utf-8   
  2.   
  3. import  os   
  4. class  dir(object):   
  5.     def  __init__( self ):   
  6.         self .SPACE = ""   
  7.         self .list = []  
  8.       
  9.     def  getCount( self , url):  
  10.         files = os.listdir(url)  
  11.         count = 0 ;  
  12.         for  file  in  files:  
  13.             myfile = url + "\\"  + file  
  14.             if  os.path.isfile(myfile):  
  15.                 count = count + 1   
  16.         return  count  
  17.     def  getDirList( self , url):   
  18.         files = os.listdir(url)   
  19.         fileNum = self .getCount(url)  
  20.         tmpNum = 0   
  21.         for  file  in  files:   
  22.             myfile = url + "\\"  + file   
  23.             size = os.path.getsize(myfile)   
  24.             if  os.path.isfile(myfile):   
  25.                 tmpNum = tmpNum +1   
  26.                 if  (tmpNum != fileNum):  
  27.                     self .list.append(str( self .SPACE) +  "├─"  + file +  "\n" )  
  28.                 else :  
  29.                     self .list.append(str( self .SPACE) +  "└─"  + file +  "\n" )  
  30.             if  os.path.isdir(myfile):   
  31.                 self .list.append(str( self .SPACE) +  "├─"  + file +  "\n" )   
  32.                 # change into sub directory   
  33.                 self .SPACE =  self .SPACE +  "│  "    
  34.                 self .getDirList(myfile)   
  35.                 # if iterator of sub directory is finished, reduce "│  "    
  36.                 self .SPACE =  self .SPACE[:- 4 ]   
  37.         return   self .list   
  38.     def  writeList( self , url):   
  39.         f = open(url, 'w' )   
  40.         f.writelines(self .list)   
  41.         print   "ok"    
  42.         f.close()   
  43. if  __name__ ==  '__main__' :   
  44.     d = dir()   
  45.     d.getDirList("c:/windows" # input directory   
  46.     d.writeList("c:/1.txt" # write to file  

产生文件的效果图:

用Python生成目录树

  • 用Python生成目录树
  • 大小: 43.7 KB

 

你可能感兴趣的:(c,windows,python,F#,OS)