繁体   English   中英

如何使用 Python 读取文件夹中的文件数?

[英]How do I read the number of files in a folder using Python?

如何使用 Python 读取特定文件夹中的文件数? 示例代码会很棒!

要非递归地计算文件和目录,可以使用os.listdir并获取其长度。

要递归计算文件和目录,可以使用os.walk迭代目录中的文件和子目录。

如果您只想计算文件而不是目录,可以使用os.listdiros.path.file来检查每个条目是否是文件:

import os.path
path = '.'
num_files = len([f for f in os.listdir(path)
                if os.path.isfile(os.path.join(path, f))])

或者使用发电机:

num_files = sum(os.path.isfile(os.path.join(path, f)) for f in os.listdir(path))

或者你可以使用os.walk如下:

len(os.walk(path).next()[2])

我从这个帖子中找到了一些这些想法。

你可以使用glob模块:

>>> import glob
>>> print len(glob.glob('/tmp/*'))
10

或者,正如Mark Byers在答案中建议的那样,如果你只想要文件:

>>> print [f for f in glob.glob('/tmp/*') if os.path.isfile(f)]
['/tmp/foo']
>>> print sum(os.path.isfile(f) for f in glob.glob('/tmp/*'))
1

马克·拜尔的回答简单,优雅,并伴随着蟒蛇精神。

但是有一个问题 :如果你尝试为“。”之外的任何其他目录运行它,它将失败,因为os.listdir()返回文件的名称,而不是完整路径。 列出当前工作目录时,这两个是相同的,因此在上面的源代码中未检测到错误。

例如,如果你在“/ home / me”并列出“/ tmp”,你就会得到(比如说)['flashXVA67']。 您将使用上述方法测试“/ home / me / flashXVA67”而不是“/ tmp / flashXVA67”。

您可以使用os.path.join()修复此问题,如下所示:

import os.path
path = './whatever'
count = len([f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))])

此外,如果您要对此进行大量计算并且需要性能,则可能需要在不生成其他列表的情况下执行此操作。 这是一个不太优雅,非常有效但高效的解决方案:

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


# The following line prints the number of files in the current directory:
path = "./whatever"
print fcount(path)

pathlib ,这是pathlib中的新功能,使得更容易。 标记为1的行生成当前文件夹的非递归列表,标记为2的递归列表。

from pathlib import Path

import os
os.chdir('c:/utilities')

print (len(list(Path('.').glob('*')))) ## 1
print (len(list(Path('.').glob('**/*')))) ## 2

还有更多的好东西。 有了这些额外的线,你可以同时看到了那些文件的项目的绝对和相对文件名。

for item in Path('.').glob('*'):
    if item.is_file():
        print (str(item), str(item.absolute()))

结果:

boxee.py c:\utilities\boxee.py
boxee_user_catalog.sqlite c:\utilities\boxee_user_catalog.sqlite
find RSS.py c:\utilities\find RSS.py
MyVideos34.sqlite c:\utilities\MyVideos34.sqlite
newsletter-1 c:\utilities\newsletter-1
notes.txt c:\utilities\notes.txt
README c:\utilities\README
saveHighlighted.ahk c:\utilities\saveHighlighted.ahk
saveHighlighted.ahk.bak c:\utilities\saveHighlighted.ahk.bak
temp.htm c:\utilities\temp.htm
to_csv.py c:\utilities\to_csv.py
total = len(filter(
            lambda f: os.path.isfile(os.path.join(path_to_dir, f)),
            os.listdir(path_to_dir)))

要么

total = sum([True for f in os.listdir(path_to_dir) if os.path.isfile(os.path.join([path_to_dir, f)])

递归解决方案:

sum(len(fs) for _,_,fs in os.walk(os.getcwd()))

对于当前目录解决方案

len(os.walk(os.getcwd()).next()[2])

试试这个:

import os
for dirpath, dirnames, filenames in os.walk('./your/folder/path'):
    print(f'There are {len(dirnames)} directories and {len(filenames)} images in {dirpath}.')

结果看起来像:

There are 10 directories and 0 images in ./asl_data/photos.
There are 0 directories and 32 images in ./asl_data/photos\0.
There are 0 directories and 34 images in ./asl_data/photos\1.
There are 0 directories and 32 images in ./asl_data/photos\2.
There are 0 directories and 31 images in ./asl_data/photos\3.
There are 0 directories and 34 images in ./asl_data/photos\4.
There are 0 directories and 31 images in ./asl_data/photos\5.
There are 0 directories and 40 images in ./asl_data/photos\6.
There are 0 directories and 33 images in ./asl_data/photos\7.
There are 0 directories and 30 images in ./asl_data/photos\8.
There are 0 directories and 39 images in ./asl_data/photos\9.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM