如何只计算目录中的文件?这将目录本身计算为一个文件:
len(glob.glob('*'))
如何只计算目录中的文件?这将目录本身计算为一个文件:
len(glob.glob('*'))
当前回答
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
摘自本文
其他回答
我用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(我在环球公司工作过一次)
简单的一个:
import os
number_of_files = len(os.listdir(directory))
print(number_of_files)
import os
print len(os.listdir(os.getcwd()))
下面是一个简单的单行命令,我觉得很有用:
print int(os.popen("ls | wc -l").read())
很简单:
print(len([iq for iq in os.scandir('PATH')]))
它只是简单地计算目录中的文件数量,我使用了列表理解技术来遍历特定目录,返回所有文件。"len(返回列表)"返回文件数。