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

len(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_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
directory_path = '/home/xyz/'
No_of_files = len(os.listdir(directory_path))
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

对于所有类型的文件,包括子目录(Python 2):

import os

lst = os.listdir(directory) # your directory path
number_files = len(lst)
print number_files

只有文件(避免子目录):

import os

onlyfiles = next(os.walk(directory))[2] #directory is your directory path as string
print len(onlyfiles)

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

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)