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

len(glob.glob('*'))

当前回答

我想扩展@Mr_and_Mrs_D的回复:

import os
folder = 'C:/Dropbox'
file_count = sum(len(files) for _, _, files in os.walk(folder))
print(file_count)

这将计算文件夹及其子文件夹中的所有文件。然而,如果你想做一些过滤——比如只计算以.svg结尾的文件,你可以这样做:

import os
file_count = sum(len([f for f in files if f.endswith('.svg')]) for _, _, files in os.walk(folder))
print(file_count)

你基本上可以替换:

len(档案)

:

Len ([f for f in files if f.endswith('.svg')])

其他回答

def count_em(valid_path):
   x = 0
   for root, dirs, files in os.walk(valid_path):
       for f in files:
            x = x+1
print "There are", x, "files in this directory."
return x

摘自本文

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

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}

我找到了另一个可能是正确的公认答案。

for root, dirs, files in os.walk(input_path):    
for name in files:
    if os.path.splitext(name)[1] == '.TXT' or os.path.splitext(name)[1] == '.txt':
        datafiles.append(os.path.join(root,name)) 


print len(files) 

我想扩展@Mr_and_Mrs_D的回复:

import os
folder = 'C:/Dropbox'
file_count = sum(len(files) for _, _, files in os.walk(folder))
print(file_count)

这将计算文件夹及其子文件夹中的所有文件。然而,如果你想做一些过滤——比如只计算以.svg结尾的文件,你可以这样做:

import os
file_count = sum(len([f for f in files if f.endswith('.svg')]) for _, _, files in os.walk(folder))
print(file_count)

你基本上可以替换:

len(档案)

:

Len ([f for f in files if f.endswith('.svg')])

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

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

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