You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言技术需求:按路径统计子文件夹文件数并判断奇偶

Python 实现方案

这里有个实用的Python脚本,完美匹配你的需求——你只需要传入目标文件夹路径,就能得到整齐的表格输出,包含子文件夹名称、文件数量和奇偶性标记:

import os

def count_files_in_subdirs(root_path):
    # 检查路径是否存在
    if not os.path.isdir(root_path):
        print(f"错误:路径 {root_path} 不存在或不是文件夹!")
        return
    
    # 准备表格表头
    print(f"| {'SUBDIRECTORY':<30} | {'# of files':<10} | {'ODD/EVEN':<8} |")
    print("|" + "-"*32 + "|" + "-"*12 + "|" + "-"*10 + "|")
    
    # 遍历所有子文件夹
    has_subdirs = False
    for entry in os.scandir(root_path):
        if entry.is_dir():
            has_subdirs = True
            # 统计当前子文件夹内的文件数量(仅统计文件,不含子文件夹)
            file_count = sum(1 for item in os.scandir(entry.path) if item.is_file())
            # 判断奇偶性
            parity = "ODD" if file_count % 2 != 0 else "EVEN"
            # 格式化输出行
            print(f"| {entry.name:<30} | {file_count:<10} | {parity:<8} |")
    
    if not has_subdirs:
        print("| 未找到任何子文件夹 |          |        |")

# 示例用法:替换成你的目标路径
if __name__ == "__main__":
    target_path = input("请输入目标文件夹路径:")
    count_files_in_subdirs(target_path)

功能说明

  • 路径校验:首先会检查你输入的路径是否有效,避免无效输入导致的报错
  • 高效统计:使用os.scandir()替代传统的os.listdir(),性能更优,还能直接判断文件类型
  • 精准计数:只统计子文件夹内的文件,不会把嵌套的子文件夹算进去
  • 整齐输出:用格式化字符串实现对齐的表格,可读性拉满
  • 边缘处理:如果目标文件夹下没有子文件夹,会给出明确提示

怎么用

  1. 把上面的代码保存为dir_file_counter.py
  2. 运行脚本,按照提示输入目标文件夹的路径(比如C:\MyFiles或者/home/user/documents)
  3. 就能看到类似下面的输出:
| SUBDIRECTORY                   | # of files  | ODD/EVEN  |
|--------------------------------|------------|----------|
| photos                         | 15         | ODD      |
| documents                      | 8          | EVEN     |
| videos                         | 0          | EVEN     |

这个脚本跨平台,Windows、Mac、Linux都能用,完全满足你的需求~

内容的提问来源于stack exchange,提问作者anakar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 00:18:11