Date
Sep. 8th, 2024
 
2024年 8月 6日

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.
反曲点科技创始人和首席执行官。
程序猿、设计师、奇怪的博主。
苹果死忠、热爱色彩斑斓的世界。
如有意向请随时 与我联系