- 論壇徽章:
- 0
|
這是一個(gè)使用Python生成文件、目錄樹的程序,其中遇到一個(gè)問題是:如何確定某個(gè)目錄下的某一文件是最后一個(gè)遍歷的文件。因?yàn)樽詈笠粋(gè)遍歷的文件前應(yīng)添加"└─",非最后一個(gè)文件前添加"├─"?戳薖ython的API文檔沒有找到相關(guān)的系統(tǒng)函數(shù)。現(xiàn)在做法是:先統(tǒng)計(jì)出某個(gè)目錄下的文件個(gè)數(shù),在遍歷目錄時(shí),當(dāng)個(gè)數(shù)相等時(shí),就可以確定該目錄遍歷結(jié)束。- # encoding: utf-8
- import os
- class dir(object):
- def __init__(self):
- self.SPACE = ""
- self.list = []
-
- def getCount(self, url):
- files = os.listdir(url)
- count = 0;
- for file in files:
- myfile = url + "\\" + file
- if os.path.isfile(myfile):
- count = count + 1
- return count
- def getDirList(self, url):
- files = os.listdir(url)
- fileNum = self.getCount(url)
- tmpNum = 0
- for file in files:
- myfile = url + "\\" + file
- size = os.path.getsize(myfile)
- if os.path.isfile(myfile):
- tmpNum = tmpNum +1
- if (tmpNum != fileNum):
- self.list.append(str(self.SPACE) + "├─" + file + "\n")
- else:
- self.list.append(str(self.SPACE) + "└─" + file + "\n")
- if os.path.isdir(myfile):
- self.list.append(str(self.SPACE) + "├─" + file + "\n")
- # change into sub directory
- self.SPACE = self.SPACE + "│ "
- self.getDirList(myfile)
- # if iterator of sub directory is finished, reduce "│ "
- self.SPACE = self.SPACE[:-4]
- 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.getDirList("c:/windows") # input directory
- d.writeList("c:/1.txt") # write to file
復(fù)制代碼 產(chǎn)生文件的效果圖:
![]() |
|