如何只计算目录中的文件?这将目录本身计算为一个文件:
len(glob.glob('*'))
如何只计算目录中的文件?这将目录本身计算为一个文件:
len(glob.glob('*'))
当前回答
import os
_, _, files = next(os.walk("/usr/lib"))
file_count = len(files)
其他回答
这就是fnmatch非常方便的地方:
import fnmatch
print len(fnmatch.filter(os.listdir(dirpath), '*.txt'))
详情:http://docs.python.org/2/library/fnmatch.html
我用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(我在环球公司工作过一次)
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
我想扩展@Mr_and_Mrs_D的回复:
import os
folder = 'C:/Dropbox'
file_count = sum(len(files) for _, _, files in os.walk(folder))
print(file_count)
这将计算文件夹及其子文件夹中的所有文件。然而,如果你想做一些过滤——比如只计算以.svg结尾的文件,你可以这样做:
import os
file_count = sum(len([f for f in files if f.endswith('.svg')]) for _, _, files in os.walk(folder))
print(file_count)
你基本上可以替换:
len(档案)
:
Len ([f for f in files if f.endswith('.svg')])
我这样做了,这返回了文件夹(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))