初学python,使用2种方法实现树形目录
方法1:
import os
path = os.getcwd()
def filenum(currPath):
'''计算当前目录下文件数'''
return sum([len(files)for root, dirs, files in os.walk(currPath)])
print('当前路径:%s' % path)
print('文件总数为:%s' % filenum(path))
def showTree(startPath):
for root, dirs, files in os.walk(startPath):
filecount = filenum(root)
level = root.replace(startPath,' ').count(os.sep)
deep = '| ' * level + '|___ '
print("%s%s" % (deep, os.path.split(root)[1]))
for file in files:
deep = '| ' * (level+1) + '|___ '
print("%s%s" %(deep, file))
showTree(path)
方法2:
import os
path = os.getcwd()
fist = path.count('/')
def all_file(currPath):
files = (os.listdir(currPath))
for file in files:
newfile = currPath + '/' + file
level = newfile.count('/')
a = level - fist
print('| ' * a + '|__ ' + file)
if os.path.isdir(newfile):
all_file(newfile)
all_file(path)
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。