如何扫描个人本机文件系统文件个数、目录个数、最大文件和最小文件、目录最大级数的源程序和结果
时间: 2024-10-11 16:07:00 浏览: 14
扫描个人电脑文件系统的文件个数、目录个数、最大和最小文件,以及查找最深目录,通常需要使用操作系统提供的API来遍历文件系统树。以下是一个基本的Python示例,使用os和shutil模块,但这仅适用于Unix-like系统(如Linux和macOS),Windows可能需要采用不同的方法:
```python
import os
import shutil
def scan_local_files(path="/", level=0):
file_count = 0
dir_count = 0
max_file_size = None
min_file_size = float('inf')
deepest_dir_level = level
for entry in os.scandir(path):
if entry.is_file():
file_count += 1
if max_file_size is None or entry.stat().st_size > max_file_size:
max_file_size = entry.stat().st_size
if entry.stat().st_size < min_file_size:
min_file_size = entry.stat().st_size
elif entry.is_dir():
dir_count += 1
deepest_dir_level = max(deepest_dir_level, level + 1)
sub_scan_path = os.path.join(path, entry.name)
# 递归遍历子目录
result = scan_local_files(sub_scan_path, level + 1)
file_count += result['file_count']
dir_count += result['dir_count']
return {
"file_count": file_count,
"dir_count": dir_count,
"max_file_size": max_file_size,
"min_file_size": min_file_size,
"deepest_dir_level": deepest_dir_level
}
# 使用函数并打印结果
result = scan_local_files()
print(f"Files: {result['file_count']}, Directories: {result['dir_count']}")
print(f"Max file size: {result['max_file_size']} bytes, Min file size: {result['min_file_size']} bytes")
print(f"Deepest directory level: {result['deepest_dir_level']}")
阅读全文