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

Python
Python入门教程 超详细1小时学会Python
复制粘贴功能的Python程序
python远程登录代码
Python Mysql自动备份脚本
py中的目录与文件判别代码
python下如何让web元素的生成更简单的分析
Python 文件操作技巧(File operation) 实例代码分析
python备份文件的脚本
Python备份Mysql脚本
rhythmbox中文名乱码问题解决方法
Python交换变量
Python字符遍历的艺术
Python字符转换
Python isinstance判断对象类型
Python ljust rjust center输出
Python strip lstrip rstrip使用方法
Python 连接字符串(join %)
Python 字符串中的字符倒转
Python translator使用实例
Python 除法小技巧

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


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-10-12   浏览: 270 ::
收藏到网摘: 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生成的好。。。。。。。