這是一個(gè)使用Python生成文件、目錄樹(shù)的程序,其中遇到一個(gè)問(wèn)題是:如何確定某個(gè)目錄下的某一文件是最后一個(gè)遍歷的文件。因?yàn)樽詈笠粋€(gè)遍歷的文件前應(yīng)添加"└─",非最后一個(gè)文件前添加"├─"。看了Python的API文檔沒(méi)有找到相關(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 + "http://" + 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 + "http://" + 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 以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林站長(zhǎng)站。
新聞熱點(diǎn)
疑難解答
圖片精選