码迷,mamicode.com
首页 > 其他好文 > 详细

生成文件夹树状图

时间:2020-01-03 15:38:06      阅读:76      评论:0      收藏:0      [点我收藏+]

标签:生成文件   ==   python   文件   listdir   ast   path   ranch   dirname   

import os
import os.path

BRANCH = ‘├─‘
LAST_BRANCH = ‘└─‘
TAB = ‘│  ‘
EMPTY_TAB = ‘   ‘


def get_dir_list(path, placeholder=‘‘):
    folder_list = [folder for folder in os.listdir(path) if os.path.isdir(os.path.join(path, folder))]
    file_list = [file for file in os.listdir(path) if os.path.isfile(os.path.join(path, file))]
    result = ‘‘
    for folder in folder_list[:-1]:
        result += placeholder + BRANCH + folder + ‘\n‘
        result += get_dir_list(os.path.join(path, folder), placeholder + TAB)
    if folder_list:
        result += placeholder + (BRANCH if file_list else LAST_BRANCH) + folder_list[-1] + ‘\n‘
        result += get_dir_list(os.path.join(path, folder_list[-1]), placeholder + (TAB if file_list else EMPTY_TAB))
    for file in file_list[:-1]:
        result += placeholder + BRANCH + file + ‘\n‘
    if file_list:
        result += placeholder + LAST_BRANCH + file_list[-1] + ‘\n‘
    return result


if __name__ == ‘__main__‘:
    print(os.path.dirname(os.getcwd()))
    print(get_dir_list(os.path.dirname(os.getcwd())))

  

生成文件夹树状图

标签:生成文件   ==   python   文件   listdir   ast   path   ranch   dirname   

原文地址:https://www.cnblogs.com/dacui/p/12145139.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!