如何只计算目录中的文件?这将目录本身计算为一个文件:

len(glob.glob('*'))

当前回答

这是一个简单的解决方案,可以计算包含子文件夹的目录中的文件数量。它可能会派上用场:

import os
from pathlib import Path

def count_files(rootdir):
    '''counts the number of files in each subfolder in a directory'''
    for path in pathlib.Path(rootdir).iterdir():
        if path.is_dir():
            print("There are " + str(len([name for name in os.listdir(path) \
            if os.path.isfile(os.path.join(path, name))])) + " files in " + \
            str(path.name))
            
 
count_files(data_dir) # data_dir is the directory you want files counted.

你应该得到一个类似这样的输出(当然,占位符改变了):

There are {number of files} files in {name of sub-folder1}
There are {number of files} files in {name of sub-folder2}

其他回答

我用glob。Iglob的目录结构类似于

data
└───train
│   └───subfolder1
│   |   │   file111.png
│   |   │   file112.png
│   |   │   ...
│   |
│   └───subfolder2
│       │   file121.png
│       │   file122.png
│       │   ...
└───test
    │   file221.png
    │   file222.png

以下两个选项都返回4(正如预期的那样,即不计算子文件夹本身)

len (list (glob。iglob(“数据/火车/ * / * . png ", recursive = True)) sum(我在环球公司工作过一次)

我这样做了,这返回了文件夹(Attack_Data)中的文件数量…这很好。

import os
def fcount(path):
    #Counts the number of files in a directory
    count = 0
    for f in os.listdir(path):
        if os.path.isfile(os.path.join(path, f)):
            count += 1

    return count
path = r"C:\Users\EE EKORO\Desktop\Attack_Data" #Read files in folder
print (fcount(path))

一行和递归:

def count_files(path):
    return sum([len(files) for _, _, files in os.walk(path)])

count_files('path/to/dir')

很简单:

print(len([iq for iq in os.scandir('PATH')]))

它只是简单地计算目录中的文件数量,我使用了列表理解技术来遍历特定目录,返回所有文件。"len(返回列表)"返回文件数。

我写的一个简单的实用函数,它使用os.scandir()而不是os.listdir()。

import os 

def count_files_in_dir(path: str) -> int:
    file_entries = [entry for entry in os.scandir(path) if entry.is_file()]

    return len(file_entries)

主要的好处是,不再需要os.path.is_file(),取而代之的是os.path.is_file()。DirEntry实例的is_file()也消除了os.path的需要。join(DIR, file_name)如其他答案所示。