Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 234
prosseek Avatar asked Apr 13 '10 18:04

prosseek


People also ask

How do I count the number of files in a directory?

To determine how many files there are in the current directory, put in ls -1 | wc -l. This uses wc to do a count of the number of lines (-l) in the output of ls -1.

How do you count the number of files in a file in Python?

Use readlines() to get Line Count This is the most straightforward way to count the number of lines in a text file in Python. The readlines() method reads all lines from a file and stores it in a list. Next, use the len() function to find the length of the list which is nothing but total lines present in a file.


1 Answers

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))]) 
like image 58
Daniel Stutzbach Avatar answered Oct 16 '22 18:10

Daniel Stutzbach