[轉載]Python 真現生成樹狀目錄和顯示文件大小


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
'''''
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")

原文: http://blog.csdn.net/dirful/archive/2009/07/23/4374953.aspx