要按子文件夹列出文件数,您可以使用递归算法遍历文件夹,并计算每个子文件夹中的文件数。以下是一个示例代码,使用Python编写:
import os
def count_files_in_folder(folder_path):
count = 0
for root, dirs, files in os.walk(folder_path):
count += len(files)
return count
def count_files_in_subfolders(folder_path):
file_counts = {}
for root, dirs, files in os.walk(folder_path):
if root != folder_path:
folder_name = os.path.basename(root)
file_count = count_files_in_folder(root)
file_counts[folder_name] = file_count
return file_counts
# 示例用法
folder_path = 'path/to/your/folder'
file_counts = count_files_in_subfolders(folder_path)
for folder_name, file_count in file_counts.items():
print(f"文件夹 {folder_name} 中的文件数: {file_count}")
在示例代码中,count_files_in_folder
函数用于计算给定文件夹中的文件数。count_files_in_subfolders
函数使用递归算法遍历文件夹及其子文件夹,并将每个子文件夹的文件数存储在一个字典 file_counts
中。然后,通过遍历字典,输出每个子文件夹的文件数。您只需要将 folder_path
替换为您要计算文件数的文件夹的路径即可使用该代码。