How to count the number of files in a directory using Python

…衆ロ難τιáo~ 提交于 2019-11-26 23:48:10

问题


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

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?


回答1:


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



回答2:


import os

path, dirs, files = next(os.walk("/usr/lib"))
file_count = len(files)


来源:https://stackoverflow.com/questions/2632205/how-to-count-the-number-of-files-in-a-directory-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!