首页 > 解决方案 > 如何找到具有目标扩展名列表的文件编号,例如:.txt、.pdf 等,并使用 python 为当前目录和子目录分别打印

问题描述

import  os

def fileCount(folder):
    "count the number of files in a directory"

    count = 0

    for filename in os.listdir(folder):
        path = os.path.join(folder, filename)

        if os.path.isfile(path):
            count += 1
        elif os.path.isdir(path):
            count += fileCount(path)
    print(folder,'having',count)
    return count
fileCount('.')

标签: pythonfile

解决方案


import glob

def countMe(MyPath,typeofFile):
    numInstances = len(glob.glob1(MyPath,'*.'+typeofFile))
    return numInstances

typeofFile应该是您要查找的扩展名的字符串。如果你正在寻找.pdf那么typeofFile = 'pdf'


推荐阅读