0

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.

4
Contributors
8
Replies
14
Views
9 Years
Discussion Span
Last Post by bimaljr
0

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

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"))
0

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
0

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(".")))))
0

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

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.