Date
Nov. 23rd, 2024
 
2024年 10月 23日

Post: Python : tree

Python : tree

Published 12:03 Mar 21, 2014.

Created by @ezra. Categorized in #Programming, and tagged as #Python.

Source format: Markdown

Table of Content

用 Python 实现一个 tree 指令的模拟,后面有时间再做优化:

import os

def main():
    while True:
        path = input('Input a path: ') + ''
        if os.path.exists(path):
            # 去掉末尾分隔符
            if path.endswith(os.sep):
                path = path[:-1]
            fileCount = 0
            directoryCount = 0
            sepFile = '|__ '
            sepDirectory = '|__ '
            sepCount = path.count(os.sep)
            # 遍历目录
            for root, dirs, files in os.walk(path):
                space = ''
                for i in range(root.count(os.sep) - sepCount):
                    space += '  '
                last = root.split(os.sep)
                print(space + sepDirectory + last[-1])
                directoryCount += 1
                # 遍历文件
                for fileName in files:
                    print(space + '  ' + sepFile + fileName)
                    fileCount += 1
            print('You have %i directories and %i files under "%s"' %(directoryCount, fileCount, path))
            break
        else:
            print('Invalid path!\n')

if __name__ == '__main__':
    main()
Pinned Message
HOTODOGO
The Founder and CEO of Infeca Technology.
Developer, Designer, Blogger.
Big fan of Apple, Love of colour.
Feel free to contact me.
反曲点科技创始人和首席执行官。
开发、设计与写作皆为所长。
热爱苹果、钟情色彩。
随时恭候 垂询