• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

Python生成目录树

python 水墨上仙 2186次浏览

Python生成目录树


# 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 


开心洋葱 , 版权所有丨如未注明 , 均为原创丨未经授权请勿修改 , 转载请注明Python生成目录树
喜欢 (0)
加载中……