当前位置: 编程技术>python
python 生成目录树及显示文件大小的代码
来源: 互联网 发布时间:2014-09-04
本文导语: 比如 1--1 2--1 2 3--1 2 3 3--1 2 3交错的层级关系,刚开始感觉很乱没有想明白,后来终于抓住了关键。只要算出每个层次的深度,就...
比如
'''
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")
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生成的好。。。。。。。