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

Source: Internet
Author: User
Like what

1--1

2--1

2

3--1

2

3

3--1

2

3

Staggered hierarchical relationship, just start feeling very messy did not want to understand, then finally caught the key. As long as the calculation of the depth of each level, it is good to do.

I define a rank, and when I go into a subfolder, let rank+1, walk through the subfolder rank-1.

The graph fully illustrates the recursion, the sequence of traversal, and the change in rank values: (Ugly point ...) )

Put the code below:

Copy Code code as follows:

'''
Created on June 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. Without the good of Microsoft tree generation ....

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.