如何只计算目录中的文件?这将目录本身计算为一个文件:
len(glob.glob('*'))
如何只计算目录中的文件?这将目录本身计算为一个文件:
len(glob.glob('*'))
当前回答
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))])
其他回答
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
一个答案与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
转换为列表后,您可以Len
len(list(glob.glob('*')))
这就是fnmatch非常方便的地方:
import fnmatch
print len(fnmatch.filter(os.listdir(dirpath), '*.txt'))
详情:http://docs.python.org/2/library/fnmatch.html
import os
print len(os.listdir(os.getcwd()))