Python实现画目录树
将任意一个文件夹的路径和文件夹名称输入,得到一颗可视化的目录树,存在一个txt文件中。要用到以下四种图像进行操作。效果如下图
│ ├ ─ └
代码如下
import os
def get_num(path):
dirlist = os.listdir(path)
j=0
for i in dirlist:
j+=1
return j
def print_tree(path,last):
num=get_num(path)
if num!=0:
dirlist = os.listdir(path)
j=0
for i in dirlist:
for k in last:
if k=='0':
print(" │",end=" ")
else:
print(" ", end=" ")
j+=1
if j<num:
print(" ├── ", end="")
print(i)
dir=path+"\\"+i
if os.path.isdir(dir):
print_tree(dir,last+'0')
else:
print(" └── ", end="")
print(i)
dir = path + "\\" + i
if os.path.isdir(dir):
print_tree(dir,last+'1')
def write_tree(path,last,f):
num=get_num(path)
if num!=0:
dirlist = os.listdir(path)
j=0
for i in dirlist:
for k in last:
if k=='0':
f.write(" │")
else:
f.write(" ")
j+=1
if j<num:
f.write(" ├── ")
f.write(i)
f.write('\n')
dir=path+"\\"+i
if os.path.isdir(dir):
write_tree(dir,last+'0',f)
else:
f.write(" └── ")
f.write(i)
f.write('\n')
dir = path + "\\" + i
if os.path.isdir(dir):
write_tree(dir,last+'1',f)
if __name__=='__main__':
path = input("请输入文件夹路径(不含名称):")
root = input("请输入文件夹名称:")
if len(path)==1:
path+=':'
#print(" └─root")
#print_tree('D:\\root',"1")
f = open("tree.txt", "w", encoding="utf-8")
f.write(" └──"+root+"\n")
write_tree(path+"\\"+root, "1",f)
f.close()
代码中的两个函数为之间显示和写入文件,采用递归的方法解决问题,穿的参数为当前目录和父目录的是否为最后一个文件。