Python遍历指定目录并以树形结构显示目录结构

2022-03-11 00:00:00 目录 遍历 结构

Python生成目录树,指定目录,这段代码可以将目录以树形结构生成目录树

"""
作者:皮蛋编程(https://www.pidancode.com)
创建日期:2022/3/18
修改日期:2022/3/18
功能描述:Python遍历指定目录并以树形结构显示目录结构
"""

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")
                # 进入子目录
                self.SPACE = self.SPACE + "│  "
                self.getDirList(myfile)
                # 如果没有子目录了则删除 "│  "符号
                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("./")  # input directory
    d.writeList("pidancode.com.txt")  # write to file </pre>

输出结果如下:

├─11.py
├─40.py
├─25.py
├─temp
│  └─pidancode.py
├─pidancode.com.txt
├─9.py
├─34.py
├─.DS_Store
├─10.py
├─24.py

以上代码在Python3.9+Mac环境下测试通过,windows下测试需要做部分修改,将表示目录路径的/替换成Windows下的\

相关文章