Home  >  Article  >  Backend Development  >  python 生成目录树及显示文件大小的代码

python 生成目录树及显示文件大小的代码

WBOY
WBOYOriginal
2016-06-06 11:26:481544browse

比如

1--1

     2--1

          2

          3--1

               2

               3

     3--1

          2

          3

交错的层级关系,刚开始感觉很乱没有想明白,后来终于抓住了关键。只要算出每个层次的深度,就好办了。

我定义了一个rank,进入一个子文件夹时,让rank+1,遍历完子文件夹rank就-1。

如图充分说明了递归、遍历的顺序以及rank值变化:(丑了点。。。)

下面放代码:

代码如下:


'''
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")


生成树如下。没有微软tree生成的好。。。。。。。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn