简体   繁体   English

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

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

How do I read the number of files in a specific folder using Python?如何使用 Python 读取特定文件夹中的文件数? Example code would be awesome!示例代码会很棒!

To count files and directories non-recursively you can use os.listdir and take its length. 要非递归地计算文件和目录,可以使用os.listdir并获取其长度。

To count files and directories recursively you can use os.walk to iterate over the files and subdirectories in the directory. 要递归计算文件和目录,可以使用os.walk迭代目录中的文件和子目录。

If you only want to count files not directories you can use os.listdir and os.path.file to check if each entry is a file: 如果您只想计算文件而不是目录,可以使用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))])

Or alternatively using a generator: 或者使用发电机:

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

Or you can use os.walk as follows: 或者你可以使用os.walk如下:

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

I found some of these ideas from this thread . 我从这个帖子中找到了一些这些想法。

You can use the glob module: 你可以使用glob模块:

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

Or, as Mark Byers suggests in his answer, if you only want files: 或者,正如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

Mark Byer's answer is simple, elegant, and goes along with the python spirit. 马克·拜尔的回答简单,优雅,并伴随着蟒蛇精神。

There's a problem, however : if you try to run that for any other directory than ".", it will fail, since os.listdir() returns the names of the files, not the full path. 但是有一个问题 :如果你尝试为“。”之外的任何其他目录运行它,它将失败,因为os.listdir()返回文件的名称,而不是完整路径。 Those two are the same when listing the current working directory, so the error goes undetected in the source above. 列出当前工作目录时,这两个是相同的,因此在上面的源代码中未检测到错误。

For example, if your at "/home/me" and you list "/tmp", you'll get (say) ['flashXVA67']. 例如,如果你在“/ home / me”并列出“/ tmp”,你就会得到(比如说)['flashXVA67']。 You'll be testing "/home/me/flashXVA67" instead of "/tmp/flashXVA67" with the method above. 您将使用上述方法测试“/ home / me / flashXVA67”而不是“/ tmp / flashXVA67”。

You can fix this using os.path.join(), like this: 您可以使用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))])

Also, if you're going to be doing this count a lot and require performance, you may want to do it without generating additional lists. 此外,如果您要对此进行大量计算并且需要性能,则可能需要在不生成其他列表的情况下执行此操作。 Here's a less elegant, unpythonesque yet efficient solution: 这是一个不太优雅,非常有效但高效的解决方案:

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 , that is new in v. 3.4, makes like easier. pathlib ,这是pathlib中的新功能,使得更容易。 The line labelled 1 makes a non-recursive list of the current folder, the one labelled 2 the recursive list. 标记为1的行生成当前文件夹的非递归列表,标记为2的递归列表。

from pathlib import Path

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

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

There are more goodies too. 还有更多的好东西。 With these additional lines you can see both the absolute and relative file names for those items that are files. 有了这些额外的线,你可以同时看到了那些文件的项目的绝对和相对文件名。

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

Result: 结果:

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)))

OR 要么

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

recursive solution: 递归解决方案:

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

for current directory solution: 对于当前目录解决方案

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

Try this:试试这个:

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}.')

The result looks would looks like:结果看起来像:

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.

相关问题 如何将文件复制到python中的只读文件夹 - How do i copy files to a read-only folder in python 如何使用python读取Windows历史记录(文件夹)的内容? - How do I read the contents of Windows History (folder) using python? Python - 如何读取以 xyz 开头的文件夹中的多个文件? - Python - How do you read multiple files in a folder starting by xyz? 如何使用 Python 在特定文件夹中找到今天创建的所有文件 - How do I find all the files that were created today in specific folder using Python 如何使用python从文件夹中的多个excel文件中读取具有“ mine”工作表名称的工作表? 我正在使用xlrd - how to read any sheet with the sheet name containing 'mine' from multiple excel files in a folder using python? i am using xlrd Python,我如何在文件夹中找到以特定格式结尾的文件 - Python, how do i find files that end with a specific format in a folder 如何选择与 python 中特定文件夹相关的文件? - How do I pick files with respect to a particular folder in python? 我如何在 python 的特定文件夹中保存.json 文件 - How do i save .json files in specific folder in python 如何打开和读取文件夹python中的文本文件 - How to open and read text files in a folder python 如何在python中读取文件夹中的txt文件列表 - how to read a list of txt files in a folder in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM