如何使用python遍历一个目录得到树结构?
可以使用os模块中的walk方法来遍历一个目录,得到该目录下所有文件和子目录的树结构。具体代码如下:
import os
def get_tree(start_path):
for root, dirs, files in os.walk(start_path):
level = root.replace(start_path, '').count(os.sep)
indent = ' ' * 4 * (level)
print(f"{indent}{os.path.basename(root)}/")
subindent = ' ' * 4 * (level + 1)
for file in files:
print(f"{subindent}{file}")
get_tree("/path/to/directory")
其中,os.walk方法返回一个三元组,分别是当前目录路径、当前目录下的子目录列表以及当前目录下的文件列表。通过循环遍历三元组,可以得到目录的树形结构。在输出时,需要根据目录的层级进行缩进,以便显示出树形结构。
原文地址: https://www.cveoy.top/t/topic/Fva 著作权归作者所有。请勿转载和采集!