效果图:
1、显示所有文件和文件夹:
import os
def list_files(startpath, prefix=''):
items = os.listdir(startpath)
items.sort()
for index, item in enumerate(items):
item_path = os.path.join(startpath, item)
is_last = index == len(items) - 1
if os.path.isdir(item_path):
print(f'{prefix}{"└── " if is_last else "├── "}{item}/')
list_files(item_path, prefix + (' ' if is_last else '│ '))
else:
print(f'{prefix}{"└── " if is_last else "├── "}{item}')
# 显示当前目录的文件树
list_files('.')
解释:
• startpath: 开始遍历的目录路径。
• prefix: 用于控制缩进的字符串,初始为空字符串。
• items: 列出指定目录下的所有文件和文件夹,并进行排序。
• index: 当前遍历的文件或文件夹在列表中的索引。
• is_last: 判断当前遍历的文件或文件夹是否是列表中的最后一个。
• item_path: 拼接路径。
• os.path.isdir(item_path): 判断给定的路径是否是一个目录。
• "└── " if is_last else "├── ": 如果当前文件或文件夹是最后一个,则使用“└── ”,否则使用“├── ”。
• prefix + (' ' if is_last else '│ '): 更新缩进字符串,如果是最后一个文件或文件夹,则使用空格,否则使用“│ ”。
def list_nofiles(startpath, prefix=''):
items = [item for item in os.listdir(startpath) if os.path.isdir(os.path.join(startpath, item))]
items.sort()
for index, item in enumerate(items):
item_path = os.path.join(startpath, item)
is_last = index == len(items) - 1
dir_prefix = '└── ' if is_last else '├── '
prefix_str = f'{prefix}{dir_prefix}{item}/'
print(prefix_str)
sub_prefix = prefix + (' ' if is_last else '│ ')
list_nofiles(item_path, sub_prefix)
# 显示当前目录的文件树
list_nofiles('.')