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

yipeiwu_com6年前Python基础
比如

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

相关文章

matplotlib在python上绘制3D散点图实例详解

matplotlib在python上绘制3D散点图实例详解

大家可以先参考官方演示文档: 效果图: ''' ============== 3D scatterplot ============== Demonstration of a ba...

Python 专题四 文件基础知识

前面讲述了函数、语句和字符串的基础知识,该篇文章主要讲述文件的基础知识(与其他语言非常类似). 一. 文件的基本操作 文件是指存储在外部介质(如磁盘)上数据的集合.文件的操作流程为: 打...

python logging类库使用例子

一、简单使用 复制代码 代码如下: def TestLogBasic():     import logging     l...

python处理文本文件并生成指定格式的文件

import os import sys import string #以指定模式打开指定文件,获取文件句柄 def getFileIns(filePath,model)...

Python中的闭包实例详解

一般来说闭包这个概念在很多语言中都有涉及,本文主要谈谈python中的闭包定义及相关用法。Python中使用闭包主要是在进行函数式开发时使用。详情分析如下: 一、定义 python中的闭...