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

如何使用Python读取文件夹中的文件数?,python,file-io,Python,File Io,如何使用Python读取特定文件夹中的文件数?示例代码将非常棒 要以非递归方式计算文件和目录,可以使用并计算其长度 要递归地计算文件和目录,可以使用迭代目录中的文件和子目录 如果只想计算文件而不是目录,可以使用os.listdir检查每个条目是否为文件: import os.path path = '.' num_files = len([f for f in os.listdir(path) if os.path.isfile(os.path.join(path

如何使用Python读取特定文件夹中的文件数?示例代码将非常棒

要以非递归方式计算文件和目录,可以使用并计算其长度


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

如果只想计算文件而不是目录,可以使用
os.listdir
检查每个条目是否为文件:

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])
我从中找到了一些想法。

您可以使用该模块:

或者,正如马克·拜尔斯(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

MarkByer的回答简单、优雅,并且符合python精神

但是有一个问题:如果您尝试对“.”以外的任何其他目录运行该命令,它将失败,因为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)
sum(len(fs) for _,_,fs in os.walk(os.getcwd()))
len(os.walk(os.getcwd()).next()[2])


pathlib
,这在v中是新的。3.4,使喜欢更容易。标记为1的行构成当前文件夹的非递归列表,标记为2的行构成递归列表

from pathlib import Path

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

print (len(list(Path('.').glob('*')))) ## 1
print (len(list(Path('.').glob('**/*')))) ## 2
还有更多的好东西。通过这些额外的行,您可以看到这些文件项的绝对和相对文件名

结果:

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
递归解决方案:

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)
sum(len(fs) for _,_,fs in os.walk(os.getcwd()))
len(os.walk(os.getcwd()).next()[2])
对于当前目录解决方案:

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)
sum(len(fs) for _,_,fs in os.walk(os.getcwd()))
len(os.walk(os.getcwd()).next()[2])

看看皮埃尔的回答,真的!看起来比我的好,如果你正在读这篇文章,请回头看看第一个答案,Mark使用walk()添加了一个选项,解决了我在一行中指出的两个问题。+1用于发现错误-我已经用你的更正版本更新了我的答案。应该说,
os.listdir('.')
包括隐藏文件(以单点开始),而
glob('./*')
没有。@lunaryorn-如果您想要在当前目录中隐藏文件,请使用
glob('.''.')
。如果您想要包括隐藏文件在内的所有内容,请使用
glob('.*')+glob('.*')
。与
iterdir
对应的
行是
print(len('..').iterdir())