37 lines
1.3 KiB
Python
37 lines
1.3 KiB
Python
import os
|
|
|
|
def print_directory_tree(start_path, exclude_hidden=True, prefix=''):
|
|
"""递归打印目录结构树"""
|
|
if not os.path.isdir(start_path):
|
|
raise ValueError("提供的路径不是一个目录")
|
|
|
|
# 获取并过滤条目
|
|
entries = os.listdir(start_path)
|
|
if exclude_hidden:
|
|
entries = [e for e in entries if not e.startswith('.')]
|
|
|
|
# 分离并排序目录和文件
|
|
dirs = sorted([e for e in entries if os.path.isdir(os.path.join(start_path, e))])
|
|
files = sorted([e for e in entries if not os.path.isdir(os.path.join(start_path, e))])
|
|
entries = dirs + files # 目录在前,文件在后
|
|
|
|
entries_count = len(entries)
|
|
for index, entry in enumerate(entries):
|
|
entry_path = os.path.join(start_path, entry)
|
|
is_last = index == entries_count - 1
|
|
|
|
# 当前条目连接符号
|
|
connector = '└── ' if is_last else '├── '
|
|
print(f"{prefix}{connector}{entry}")
|
|
|
|
if os.path.isdir(entry_path):
|
|
# 下一级缩进前缀
|
|
extension = ' ' if is_last else '│ '
|
|
print_directory_tree(entry_path, exclude_hidden, prefix + extension)
|
|
|
|
if __name__ == "__main__":
|
|
import sys
|
|
path = r"C:\Users\yilv\Desktop\normwear\NormWear"
|
|
print(f"目录结构:{os.path.abspath(path)}")
|
|
print_directory_tree(path)
|