Python generates the directory tree and the code that displays the file size

  • 2020-04-02 09:19:03
  • OfStack

Such as

1-1

      2-1

            2

            3-1

                2

                3

      3-1

            2

            3

The interlacing of the hierarchy, at first felt very messy did not understand, then finally caught the key. Just figure out the depth of each level.

I've defined a rank, and when I go into a subfolder, I put rank plus 1, and when I go through the subfolder, rank minus 1.

The figure fully illustrates recursion, traversal order, and rank changes :(ugly...)
< img Alt = "" border = 0 height = 400 SRC =" http://files.jb51.net/upload/20090723233213730.JPG "width = 640 >
Here's the code:


''' 
Created on Jul 22, 2009 

@author: dirful 
''' 
import os 
class dir(object): 

def __init__(self): 
self.CONST =0 
self.SPACE ="" 
self.list =[] 
def p(self,url): 
files = os.listdir(r''+url) 
for file in files: 
myfile = url + "\"+file 
size = os.path.getsize(myfile) 
if os.path.isfile(myfile): 
self.list.append(str(self.SPACE)+"|____"+file +" "+ str(size)+"n") 
# print str(self.SPACE)+"|____"+file +" "+ str(size) 

if os.path.isdir(myfile) : 
self.list.append(str(self.SPACE)+"|____"+file + "n") 
#get into the sub-directory,add "| " 
self.SPACE = self.SPACE+"| " 
self.p(myfile) 
#when sub-directory of iteration is finished,reduce "| " 
self.SPACE = self.SPACE[:-5] 
return self.list 

def writeList(self,url): 
f = open(url,'w') 
f.writelines(self.list) 
print "ok" 
f.close() 



if __name__ == '__main__': 
d=dir() 
d.p("E:/eclipse") 
d.writeList("c:3.txt")

The spanning tree is as follows. Not as good as Microsoft tree...

< img Alt = "" border = 0 height = 455 SRC =" http://files.jb51.net/upload/20090723233213994.jpg "width = 474 >


Related articles: