您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

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

2024/7/9 21:44:34发布33次查看
比如
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生成的好。。。。。。。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product