如何只计算目录中的文件?这将目录本身计算为一个文件:
len(glob.glob('*'))
如何只计算目录中的文件?这将目录本身计算为一个文件:
len(glob.glob('*'))
当前回答
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
其他回答
虽然我同意@DanielStutzbach提供的答案:os.listdir()将比使用glob.glob更有效。
然而,额外的精度,如果你想计算文件夹中特定文件的数量,你想使用len(glob.glob())。例如,如果你要计算你想要使用的文件夹中的所有pdf文件:
pdfCounter = len(glob.glob1(myPath,"*.pdf"))
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))])
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)
这是一个简单的解决方案,可以计算包含子文件夹的目录中的文件数量。它可能会派上用场:
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}
如果您将使用操作系统的标准shell,则可以比使用纯python方式更快地获得结果。
Windows示例:
import os
import subprocess
def get_num_files(path):
cmd = 'DIR \"%s\" /A-D /B /S | FIND /C /V ""' % path
return int(subprocess.check_output(cmd, shell=True))