初學(xué)python,使用2種方法實(shí)現(xiàn)樹形目錄
方法1:
import os
path = os.getcwd()
def filenum(currPath):
'''計(jì)算當(dāng)前目錄下文件數(shù)'''
return sum([len(files)for root, dirs, files in os.walk(currPath)])
print('當(dāng)前路徑:%s' % path)
print('文件總數(shù)為:%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)
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。