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

len(glob.glob('*'))

当前回答

下面是一个简单的单行命令,我觉得很有用:

print int(os.popen("ls | wc -l").read())

其他回答

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

一行和递归:

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

count_files('path/to/dir')

我用glob。Iglob的目录结构类似于

data
└───train
│   └───subfolder1
│   |   │   file111.png
│   |   │   file112.png
│   |   │   ...
│   |
│   └───subfolder2
│       │   file121.png
│       │   file122.png
│       │   ...
└───test
    │   file221.png
    │   file222.png

以下两个选项都返回4(正如预期的那样,即不计算子文件夹本身)

len (list (glob。iglob(“数据/火车/ * / * . png ", recursive = True)) sum(我在环球公司工作过一次)

卢克的代码重新格式化。

import os

print len(os.walk('/usr/lib').next()[2])