本文目录导读:

Python 实现
基础版本
import os
def print_directory_tree(path, indent=''):
"""打印目录树结构"""
items = os.listdir(path)
items.sort()
for i, item in enumerate(items):
is_last = i == len(items) - 1
item_path = os.path.join(path, item)
# 选择连接符号
if is_last:
print(indent + '└── ' + item)
new_indent = indent + ' '
else:
print(indent + '├── ' + item)
new_indent = indent + '│ '
# 如果是目录,递归打印
if os.path.isdir(item_path):
print_directory_tree(item_path, new_indent)
# 使用示例
print_directory_tree('.')
增强版本(带文件大小和权限)
import os
import stat
def get_file_info(path):
"""获取文件信息"""
st = os.stat(path)
size = st.st_size
perms = stat.filemode(st.st_mode)
return f"[{perms}] {format_size(size)}"
def format_size(size):
"""格式化文件大小"""
for unit in ['B', 'KB', 'MB', 'GB']:
if size < 1024:
return f"{size:.1f}{unit}"
size /= 1024
return f"{size:.1f}TB"
def print_enhanced_tree(path, indent='', prefix=''):
"""增强版目录树打印"""
items = os.listdir(path)
items.sort()
for i, item in enumerate(items):
is_last = i == len(items) - 1
item_path = os.path.join(path, item)
# 构建连接符号
connector = '└── ' if is_last else '├── '
# 获取文件信息
try:
info = get_file_info(item_path) if os.path.isfile(item_path) else ''
except:
info = ''
print(f"{prefix}{connector}{item} {info}")
# 递归处理子目录
if os.path.isdir(item_path):
new_prefix = prefix + (' ' if is_last else '│ ')
print_enhanced_tree(item_path, indent, new_prefix)
# 使用示例
print_enhanced_tree('.')
Bash/Shell 实现
基础 tree 命令
# 系统自带命令 tree # 自定义选项 tree -L 2 # 只显示2层 tree -d # 只显示目录 tree -a # 显示隐藏文件 tree -h # 显示文件大小 tree -I '*.pyc' # 排除.pyc文件
自定义 Shell 脚本
#!/bin/bash
print_tree() {
local dir=$1
local prefix=$2
local files=()
# 读取目录内容
while IFS= read -r -d '' file; do
files+=("$file")
done < <(find "$dir" -maxdepth 1 -mindepth 1 -print0 | sort -z)
local count=${#files[@]}
local index=0
for file in "${files[@]}"; do
local name=$(basename "$file")
local is_last=false
if [ $((index)) -eq $((count - 1)) ]; then
is_last=true
fi
# 选择连接符号
if $is_last; then
echo "${prefix}└── $name"
new_prefix="${prefix} "
else
echo "${prefix}├── $name"
new_prefix="${prefix}│ "
fi
# 递归处理子目录
if [ -d "$file" ]; then
print_tree "$file" "$new_prefix"
fi
((index++))
done
}
# 使用示例
print_tree "." ""
Node.js 实现
const fs = require('fs');
const path = require('path');
function printDirectoryTree(dirPath, indent = '') {
const items = fs.readdirSync(dirPath).sort();
items.forEach((item, index) => {
const isLast = index === items.length - 1;
const itemPath = path.join(dirPath, item);
const stats = fs.statSync(itemPath);
// 选择连接符号
const connector = isLast ? '└── ' : '├── ';
const newIndent = indent + (isLast ? ' ' : '│ ');
// 添加文件类型标识
const typeSymbol = stats.isDirectory() ? '📁 ' : '📄 ';
console.log(indent + connector + typeSymbol + item);
// 递归处理子目录
if (stats.isDirectory()) {
printDirectoryTree(itemPath, newIndent);
}
});
}
// 使用示例
printDirectoryTree('.');
高级功能实现
排除文件和目录
import os
def print_filtered_tree(path, exclude_dirs=None, exclude_files=None, indent=''):
"""带过滤功能的目录树打印"""
if exclude_dirs is None:
exclude_dirs = {'.git', '__pycache__', 'node_modules'}
if exclude_files is None:
exclude_files = {'.DS_Store', '*.pyc'}
items = os.listdir(path)
items.sort()
for i, item in enumerate(items):
# 过滤排除项
if item in exclude_dirs:
continue
if any(item.endswith(ext) for ext in exclude_files):
continue
is_last = i == len([x for x in items if x not in exclude_dirs and
not any(x.endswith(ext) for ext in exclude_files)]) - 1
item_path = os.path.join(path, item)
# 打印
if is_last:
print(indent + '└── ' + item)
new_indent = indent + ' '
else:
print(indent + '├── ' + item)
new_indent = indent + '│ '
if os.path.isdir(item_path):
print_filtered_tree(item_path, exclude_dirs, exclude_files, new_indent)
# 使用示例
print_filtered_tree('.')
保存到文件
import os
import sys
class TreePrinter:
def __init__(self, output_file=None):
self.output = open(output_file, 'w') if output_file else sys.stdout
def print(self, text):
self.output.write(text + '\n')
def print_tree(self, path, indent=''):
items = os.listdir(path)
items.sort()
for i, item in enumerate(items):
is_last = i == len(items) - 1
item_path = os.path.join(path, item)
connector = '└── ' if is_last else '├── '
self.print(indent + connector + item)
if os.path.isdir(item_path):
new_indent = indent + (' ' if is_last else '│ ')
self.print_tree(item_path, new_indent)
def __del__(self):
if hasattr(self, 'output') and self.output != sys.stdout:
self.output.close()
# 保存到文件
printer = TreePrinter('tree.txt')
printer.print_tree('.')
跨平台兼容版本
import os
import sys
def print_tree_compatible(startpath):
"""兼容不同终端的目录树打印"""
# 检查是否支持 Unicode
use_unicode = sys.platform != 'win32' or os.environ.get('TERM', '').lower() != 'dumb'
connectors = {
'branch': '├── ' if use_unicode else '|-- ',
'last': '└── ' if use_unicode else '`-- ',
'vertical': '│ ' if use_unicode else '| ',
'space': ' ' if use_unicode else ' '
}
def print_tree(path, prefix=''):
items = os.listdir(path)
items.sort()
for i, item in enumerate(items):
is_last = i == len(items) - 1
item_path = os.path.join(path, item)
connector = connectors['last'] if is_last else connectors['branch']
print(prefix + connector + item)
if os.path.isdir(item_path):
new_prefix = prefix + (connectors['space'] if is_last else connectors['vertical'])
print_tree(item_path, new_prefix)
print_tree(startpath)
# 使用示例
print_tree_compatible('.')
使用建议
- 简单使用:直接用系统自带的
tree命令 - Python项目:使用 Python 版本,可自定义过滤规则
- Node.js项目:使用 JavaScript 版本
- Shell脚本:使用 Bash 版本,适合自动化脚本
- 跨平台:使用兼容版本,考虑不同终端的字符支持
选择适合你需求的版本,如果需要特定功能(如过滤、保存到文件、统计信息等),可以相应修改代码。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播