当前位置: 首页 > 图文教程 > 脚本技术 > Python > python 生成目录树及显示文件大小的代码

Python
python 正则式使用心得
python 正则式 概述及常用字符
用python分割TXT文件成4K的TXT文件
python getopt 参数处理小示例
python 运算符 供重载参考
python 查找文件夹下所有文件 实现代码
打印出python 当前全局变量和入口参数的所有属性
python 解析html之BeautifulSoup
python self,cls,decorator的理解
python 自动提交和抓取网页
python 域名分析工具实现代码
Python 文件重命名工具代码
python 提取文件的小程序
Python 网络编程说明
python 简易计算器程序,代码就几行
python encode和decode的妙用
Python开发编码规范
学习python (1)
学习python (2)
简明 Python 基础学习教程

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


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-10-12   浏览: 271 ::
收藏到网摘: n/a

没啥技术含量,大家都说没用,只不过算法还有点意思。自己憋出来的,不知道是不是跟别人的一样。做递归得到子文件夹以及文件并不难,但是能够打印出树形,层次关系展示出来,有些难度。 比如

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生成的好。。。。。。。