python 生成目錄樹及顯示文件大小的代碼
更新時間:2009年07月23日 23:32:15 作者:
沒啥技術含量,大家都說沒用,只不過算法還有點意思。自己憋出來的,不知道是不是跟別人的一樣。做遞歸得到子文件夾以及文件并不難,但是能夠打印出樹形,層次關系展示出來,有些難度。
比如
'''
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")
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生成的好。。。。。。。

相關文章
使用Python中PDB模塊中的命令來調(diào)試Python代碼的教程
這篇文章主要介紹了使用Python中PDB模塊中的命令來調(diào)試Python代碼的教程,包括設置斷點來修改代碼等、對于Python團隊項目工作有一定幫助,需要的朋友可以參考下2015-03-03
5個Python中實現(xiàn)文字轉(zhuǎn)語音模塊的使用講解
這篇文章主要為大家詳細介紹了5個Python中實現(xiàn)文字轉(zhuǎn)語音模塊的使用,文中的示例代碼講解詳細,對我們深入掌握Python有一定的幫助,需要的可以參考下2023-11-11

