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

len(glob.glob('*'))

当前回答

我解决了这个问题,同时通过谷歌Colab计算谷歌驱动器目录中的文件数量,通过将自己定向到目录文件夹by

import os                                                                                                
%cd /content/drive/My Drive/  
print(len([x for x in os.listdir('folder_name/']))  

普通用户可以尝试

 import os                                                                                                     
 cd Desktop/Maheep/                                                     
 print(len([x for x in os.listdir('folder_name/']))  

其他回答

我很惊讶没有人提到os.scandir:

def count_files(dir):
    return len([1 for x in list(os.scandir(dir)) if x.is_file()])

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

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) 
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)

我写的一个简单的实用函数,它使用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
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}