初学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)