如何使用Python读取文件夹中的文件数量? [英] How do I read the number of files in a folder using Python?

查看:677
本文介绍了如何使用Python读取文件夹中的文件数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

要非递归地计算文件和目录,您可以使用 os.listdir 并取其长度。为了递归地计算文件和目录,你可以使用 b
$ b

noreferrer> os.walk 来迭代目录中的文件和子目录。



你只想计算文件而不是你可以使用的目录 os.listdir os.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))])



或者使用属tor:

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

也可以使用 os.walk ,如下所示:

$ $ $ $ $ $ $ len $($)

我从 this thread


How do I read the number of files in a specific folder using Python? Example code would be awesome!

解决方案

To count files and directories non-recursively you can use os.listdir and take its length.

To count files and directories recursively you can use os.walk to iterate over the files and subdirectories in the directory.

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:

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:

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

I found some of these ideas from this thread.

这篇关于如何使用Python读取文件夹中的文件数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆