如何使用Python计算目录中的文件数

pro*_*eek 196 python glob count fnmatch

我需要使用Python计算目录中的文件数.我想最简单的方法是len(glob.glob('*')),但这也将目录计为文件.

有没有办法只计算目录中的文件?

Dan*_*ach 241

os.listdir()比使用效率略高glob.glob.要测试文件名是普通文件(而不是目录或其他实体),请使用os.path.isfile():

import os, os.path

# simple version for working with CWD
print len([name for name in os.listdir('.') if os.path.isfile(name)])

# path joining version for other paths
DIR = '/tmp'
print len([name for name in os.listdir(DIR) if os.path.isfile(os.path.join(DIR, name))])
Run Code Online (Sandbox Code Playgroud)

  • 如果你不在cwd上,请记得在`os.path.filename(name)`中添加`folder_path`.http://stackoverflow.com/questions/17893542/why-do-os-path-isfile-return-false (12认同)
  • 对于使用 python3 的用户, print(len(os.listdir('DIRECTORY_PATH'))) (11认同)
  • 对于嵌套在目录中的文件的递归计数,使用os.walk()解决方案可能会更好. (4认同)
  • 使用 `os.path.join(DIR, name)` 比使用 `DIR + '/' + name` 有什么好处?后者更短,而且在 IMO 上比前者更清晰。也许有一些操作系统:后者会失败? (3认同)
  • @HelloGoodbye 这正是原因。 (2认同)

Luk*_*uke 84

import os

path, dirs, files = next(os.walk("/usr/lib"))
file_count = len(files)
Run Code Online (Sandbox Code Playgroud)

  • 在Python 3中,[使用`path,dirs,files = os.walk("/ usr/lib").__ next __()`而不是](/sf/ask/75137751/可见在-蟒蛇-3-0). (7认同)
  • 或者对于交叉版本compat`next(os.walk("/ usr/lib"))` (5认同)
  • 这不是递归的 (5认同)
  • OP没有要求它是递归的 (2认同)

Gui*_*ira 41

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

import os

list = os.listdir(dir) # dir is your directory path
number_files = len(list)
print number_files
Run Code Online (Sandbox Code Playgroud)

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

import os

onlyfiles = next(os.walk(dir))[2] #dir is your directory path as string
print len(onlyfiles)
Run Code Online (Sandbox Code Playgroud)

  • 这不是递归的 (2认同)
  • 编辑队列已满,所以...请不要使用内置函数(列表、目录)作为变量名或占位符! (2认同)

nge*_*eek 30

这就是fnmatch非常方便的地方:

import fnmatch

print len(fnmatch.filter(os.listdir(dirpath), '*.txt'))
Run Code Online (Sandbox Code Playgroud)

更多细节:http://docs.python.org/2/library/fnmatch.html

  • 如果你知道你正在寻找的模式,而不是用`os.path.isfile()`来测试每个文件,那么这个速度要快得多(大约有一半时间用我在10,000个文件的目录上进行测试) .也明显快于`glob.glob()`. (3认同)

小智 23

简短而简单

import os
directory_path = '/home/xyz/'
No_of_files = len(os.listdir(directory_path))
Run Code Online (Sandbox Code Playgroud)


ras*_*ash 12

import os
print len(os.listdir(os.getcwd()))
Run Code Online (Sandbox Code Playgroud)

  • 这有时可能很有用,但它也包括计数中的子目录 (2认同)

小智 10

def directory(path,extension):
  list_dir = []
  list_dir = os.listdir(path)
  count = 0
  for file in list_dir:
    if file.endswith(extension): # eg: '.txt'
      count += 1
  return count
Run Code Online (Sandbox Code Playgroud)


Mr_*_*s_D 9

如果要计算目录中的所有文件 - 包括子目录中的文件,最pythonic方式是:

import os

file_count = sum(len(files) for _, _, files in os.walk(r'C:\Dropbox'))
print(file_count)
Run Code Online (Sandbox Code Playgroud)

我们使用比显式添加文件计数更快的总和(正在等待的时间)

  • 这是完全递归的,可能是这里最好的答案。 (3认同)

qed*_*qed 8

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

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


LBe*_*Bes 8

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

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

pdfCounter = len(glob.glob1(myPath,"*.pdf"))
Run Code Online (Sandbox Code Playgroud)


joa*_*uin 7

os.listdir适用于任何目录:

import os
directory = 'mydirpath'

number_of_files = len([item for item in os.listdir(directory) if os.path.isfile(os.path.join(directory, item))])
Run Code Online (Sandbox Code Playgroud)

使用发电机可以简化这一过程,并且可以通过以下方式加快:

import os
isfile = os.path.isfile
join = os.path.join

directory = 'mydirpath'
number_of_files = sum(1 for item in os.listdir(directory) if isfile(join(directory, item)))
Run Code Online (Sandbox Code Playgroud)


Pau*_*aul 7

使用 pathlib 并且不将整个列表加载到内存中的答案:

from pathlib import Path

path = Path('.')

print(sum(1 for _ in path.glob('*')))  # Files and folders, not recursive
print(sum(1 for _ in path.glob('**/*')))  # Files and folders, recursive

print(sum(1 for x in path.glob('*') if x.is_file()))  # Only files, not recursive
print(sum(1 for x in path.glob('**/*') if x.is_file()))  # Only files, recursive
Run Code Online (Sandbox Code Playgroud)

  • 或者只是 `sum(1 for _ in path.iterdir())` 或 `sum(1 for _, x in enumerate(path.iterdir()) if x.is_file())`。不是递归的。 (3认同)
  • 迄今为止最好的答案! (2认同)

MLD*_*Dev 6

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

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.
Run Code Online (Sandbox Code Playgroud)

您应该得到与此类似的输出(当然,占位符已更改):

There are {number of files} files in {name of sub-folder1}
There are {number of files} files in {name of sub-folder2}
Run Code Online (Sandbox Code Playgroud)


Kri*_*ian 5

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
Run Code Online (Sandbox Code Playgroud)

取自这篇文章

  • 1.`files'是一个列表。2. OP不在寻找递归计数 (2认同)

jua*_*aza 5

一行和递归:

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

count_files('path/to/dir')
Run Code Online (Sandbox Code Playgroud)