如何使用Python计算目录中的文件数 [英] How to count the number of files in a directory using Python

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

问题描述

我需要使用 Python 计算目录中的文件数.

I need to count the number of files in a directory using Python.

我想最简单的方法是len(glob.glob('*')),但这也将目录本身视为一个文件.

I guess the easiest way is len(glob.glob('*')), but that also counts the directory itself as a file.

有没有办法只计算目录中的文件?

Is there any way to count only the files in a directory?

推荐答案

os.listdir() 将比使用 glob.glob 稍微高效一些.要测试文件名是否是普通文件(而不是目录或其他实体),请使用 os.path.isfile():

os.listdir() will be slightly more efficient than using glob.glob. To test if a filename is an ordinary file (and not a directory or other entity), use os.path.isfile():

import os, os.path

# simple version for working with CWD
print len([name for name in os.listdir('.') if os.path.isfile(name)])

# path joining version for other paths
DIR = '/tmp'
print len([name for name in os.listdir(DIR) if os.path.isfile(os.path.join(DIR, name))])

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

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