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

len(glob.glob('*'))

当前回答

虽然我同意@DanielStutzbach提供的答案:os.listdir()将比使用glob.glob更有效。

然而,额外的精度,如果你想计算文件夹中特定文件的数量,你想使用len(glob.glob())。例如,如果你要计算你想要使用的文件夹中的所有pdf文件:

pdfCounter = len(glob.glob1(myPath,"*.pdf"))

其他回答

import os

def count_files(in_directory):
    joiner= (in_directory + os.path.sep).__add__
    return sum(
        os.path.isfile(filename)
        for filename
        in map(joiner, os.listdir(in_directory))
    )

>>> count_files("/usr/lib")
1797
>>> len(os.listdir("/usr/lib"))
2049

我写的一个简单的实用函数,它使用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)如其他答案所示。

简单的一个:

import os
number_of_files = len(os.listdir(directory))
print(number_of_files)

这就是fnmatch非常方便的地方:

import fnmatch

print len(fnmatch.filter(os.listdir(dirpath), '*.txt'))

详情:http://docs.python.org/2/library/fnmatch.html

虽然我同意@DanielStutzbach提供的答案:os.listdir()将比使用glob.glob更有效。

然而,额外的精度,如果你想计算文件夹中特定文件的数量,你想使用len(glob.glob())。例如,如果你要计算你想要使用的文件夹中的所有pdf文件:

pdfCounter = len(glob.glob1(myPath,"*.pdf"))