如何只计算目录中的文件?这将目录本身计算为一个文件:
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
摘自本文
其他回答
import os
print len(os.listdir(os.getcwd()))
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
摘自本文
我这样做了,这返回了文件夹(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))
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
卢克的代码重新格式化。
import os
print len(os.walk('/usr/lib').next()[2])