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
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
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
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
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
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