如何只计算目录中的文件?这将目录本身计算为一个文件:
len(glob.glob('*'))
如何只计算目录中的文件?这将目录本身计算为一个文件:
len(glob.glob('*'))
当前回答
这就是fnmatch非常方便的地方:
import fnmatch
print len(fnmatch.filter(os.listdir(dirpath), '*.txt'))
详情:http://docs.python.org/2/library/fnmatch.html
其他回答
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))])
我这样做了,这返回了文件夹(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))
转换为列表后,您可以Len
len(list(glob.glob('*')))
卢克的代码重新格式化。
import os
print len(os.walk('/usr/lib').next()[2])
简短而简单
import os
directory_path = '/home/xyz/'
No_of_files = len(os.listdir(directory_path))