如何只计算目录中的文件?这将目录本身计算为一个文件:
len(glob.glob('*'))
如何只计算目录中的文件?这将目录本身计算为一个文件:
len(glob.glob('*'))
当前回答
我这样做了,这返回了文件夹(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))
其他回答
如果您将使用操作系统的标准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))
转换为列表后,您可以Len
len(list(glob.glob('*')))
我这样做了,这返回了文件夹(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))
一个答案与pathlib和没有加载到内存的整个列表:
from pathlib import Path
path = Path('.')
print(sum(1 for _ in path.glob('*'))) # Files and folders, not recursive
print(sum(1 for _ in path.glob('**/*'))) # Files and folders, recursive
print(sum(1 for x in path.glob('*') if x.is_file())) # Only files, not recursive
print(sum(1 for x in path.glob('**/*') if x.is_file())) # Only files, recursive
对于所有类型的文件,包括子目录(Python 2):
import os
lst = os.listdir(directory) # your directory path
number_files = len(lst)
print number_files
只有文件(避免子目录):
import os
onlyfiles = next(os.walk(directory))[2] #directory is your directory path as string
print len(onlyfiles)