英文取名

V1

2022/08/06阅读:26主题:默认主题

一句话打印出文件夹及文件的树状结构图

有时想快速浏览某个指定文件夹下所有的文件和子文件夹,而不是手动地逐个展开查找,把下面的Py文件丢到文件夹里运行,打印出像我阅(xia)读(zai)的这些论文列表效果一样。

import os 
def realname(path, root=None):
    if root is not None:
        path=os.path.join(root, path)
    result=os.path.basename(path)
    if os.path.islink(path):
        realpath=os.readlink(path)
        result= '%s -> %s' % (os.path.basename(path), realpath)
    return result

def ptree(startpath, depth=-1):
    prefix=0
    if startpath != '/':
        if startpath.endswith('/'): startpath=startpath[:-1]
        prefix=len(startpath)
    for root, dirs, files in os.walk(startpath):
        level = root[prefix:].count(os.sep)
        if depth >-1 and level > depth: continue
        indent=subindent =''
        if level > 0:
            indent = '|   ' * (level-1) + '|-- '
        subindent = '|   ' * (level) + '|-- '
        print('{}{}/'.format(indent, realname(root)))
        # print dir only if symbolic link; otherwise, will be printed as root
        for d in dirs:
            if os.path.islink(os.path.join(root, d)):
                print('{}{}'.format(subindent, realname(d, root=root)))
        for f in files:
            print('{}{}'.format(subindent, realname(f, root=root)))


if __name__ == "__main__":
    ptree(r'.',1)#参数分别表示当前文件夹路径和遍历的目录层数

代码出处:https://stackoverflow.com/a/45599996/591587 关注公众号 “乐享Python”,查阅教育资源干货。

分类:

后端

标签:

Python

作者介绍

英文取名
V1