Hi
I just want to count files of particular type (like *.txt) in a folder.

I searched net and found this for all files count :
file_count = len(os.walk(valid_path).next()[2])

But I need perticuler type like *.txt . (means how many .txt files in folder)

How to do this ?
Thanks in advance.

Recommended Answers

All 8 Replies

You can filter the list like this

file_count = len([f for f in os.walk(".").next()[2] if f[-4:] == ".txt"])

You can filter the list like this

file_count = len([f for f in os.walk(".").next()[2] if f[-4:] == ".txt"])

Thanks it works.. but I want the number... not the file list

With os.walk(".").next()[2] , you already have a file list. You don't see it because you take it's len(...) :)

Yes.. You are right again...

Thanks a lot...

Be aware that your file extension may not always be .txt, but also could be be .TXT or .tXt or txT or such. To get a full count of all of these mixed case extensions it is best to use module glob ...

# to also count mixed case file extensions like .TXT or .Txt etc.
# use module glob ...
import glob

# use current directory
# or change with os.chdir(directory_name)
print "Number of .txt files =", len(glob.glob("*.txt"))

I prefer this method

import os
path = ('c:\\stuff\\countfiles\\')
print "Counting all .txt files in: " + path
x=0
for files in os.listdir(path):
    if files.endswith('.txt'):
        x+=1
        print "\nFile #" + str(x) + ": " + files
print "\nTotal number of .txt files in: " + path + " -"
print x

try this:

import os, sys
print "Total: %d .txt files" % len(map(lambda f: sys.stdout.write(f+"\n"),sorted(filter(lambda f: f.endswith(".txt"), os.listdir(".")))))

Thanks to all of you.. I just need it... thanks again :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.