954,541 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

How to count files of particular type (like *.txt) in a folder

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.

bimaljr
Junior Poster in Training
51 posts since Oct 2006
Reputation Points: 10
Solved Threads: 0
 

You can filter the list like this

file_count = len([f for f in os.walk(".").next()[2] if f[-4:] == ".txt"])
Gribouillis
Posting Maven
Moderator
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691
 

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

bimaljr
Junior Poster in Training
51 posts since Oct 2006
Reputation Points: 10
Solved Threads: 0
 

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

Gribouillis
Posting Maven
Moderator
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691
 

Yes.. You are right again...

Thanks a lot...

bimaljr
Junior Poster in Training
51 posts since Oct 2006
Reputation Points: 10
Solved Threads: 0
 

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"))
vegaseat
DaniWeb's Hypocrite
Moderator
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
 

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
Shadow14l
Light Poster
39 posts since May 2008
Reputation Points: 10
Solved Threads: 8
 

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(".")))))
Gribouillis
Posting Maven
Moderator
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691
 

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

bimaljr
Junior Poster in Training
51 posts since Oct 2006
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You