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

len(glob.glob('*'))

当前回答

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

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

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

其他回答

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

摘自本文

我这样做了,这返回了文件夹(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))

转换为列表后,您可以Len

len(list(glob.glob('*')))

import os

total_con=os.listdir('<directory path>')

files=[]

for f_n in total_con:
   if os.path.isfile(f_n):
     files.append(f_n)


print len(files)

一行和递归:

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

count_files('path/to/dir')