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.

Dani AI

Generated

If you only need a number, avoid building full lists. In modern Python, pathlib plus generator expressions is fast and readable, and you can make the check case-insensitive so .txt, .TXT, etc. are all counted (note that case sensitivity depends on the filesystem; Windows is usually case-insensitive, Unix-like systems are not). Non-recursive and recursive variants:

from pathlib import Path

root = Path("path/to/folder")

# Non-recursive, case-insensitive
count = sum(1 for p in root.iterdir()
            if p.is_file() and p.suffix.casefold() == ".txt")

# Recursive, case-insensitive
count_recursive = sum(1 for p in root.rglob("*")
                      if p.is_file() and p.suffix.casefold() == ".txt")

For huge trees, an iterator-based glob avoids holding filenames in memory. This is recursive and counts only files; the .lower() makes it robust across mixed-case extensions on POSIX too:

import os, glob

count = sum(1 for path in glob.iglob("**/*", recursive=True)
            if os.path.isfile(path) and path.lower().endswith(".txt"))

pathlib methods are documented at pathlib — Object-oriented filesystem paths. Recursive globbing with iterators is covered in glob — Unix style pathname pattern expansion. For very large directories, os.scandir() (used under the hood by pathlib) is significantly faster than os.listdir(); see os — Miscellaneous operating system interfaces.

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.