如何只计算目录中的文件?这将目录本身计算为一个文件:
len(glob.glob('*'))
如何只计算目录中的文件?这将目录本身计算为一个文件:
len(glob.glob('*'))
当前回答
虽然我同意@DanielStutzbach提供的答案:os.listdir()将比使用glob.glob更有效。
然而,额外的精度,如果你想计算文件夹中特定文件的数量,你想使用len(glob.glob())。例如,如果你要计算你想要使用的文件夹中的所有pdf文件:
pdfCounter = len(glob.glob1(myPath,"*.pdf"))
其他回答
我这样做了,这返回了文件夹(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))
我写的一个简单的实用函数,它使用os.scandir()而不是os.listdir()。
import os
def count_files_in_dir(path: str) -> int:
file_entries = [entry for entry in os.scandir(path) if entry.is_file()]
return len(file_entries)
主要的好处是,不再需要os.path.is_file(),取而代之的是os.path.is_file()。DirEntry实例的is_file()也消除了os.path的需要。join(DIR, file_name)如其他答案所示。
我找到了另一个可能是正确的公认答案。
for root, dirs, files in os.walk(input_path):
for name in files:
if os.path.splitext(name)[1] == '.TXT' or os.path.splitext(name)[1] == '.txt':
datafiles.append(os.path.join(root,name))
print len(files)
简短而简单
import os
directory_path = '/home/xyz/'
No_of_files = len(os.listdir(directory_path))
我很惊讶没有人提到os.scandir:
def count_files(dir):
return len([1 for x in list(os.scandir(dir)) if x.is_file()])