PYnative

Python Programming

  • Learn Python
  • Exercises
  • Quizzes
  • Code Editor
  • Tricks
Home » Python » File Handling » Python Count Number of Files in a Directory

Python Count Number of Files in a Directory

Updated on: January 19, 2022 | 2 Comments

In this article, we will see how to count the number of files present in a directory in Python.

If the directory contains many files and you want to count the number of files present in a directory before performing any operations. For example, you want to move all files from one directory to another. Still, before moving them, we can count how many files are present in a directory to understand its impact and the time required to perform that operation.

There are multiple ways to count files of a directory. We will use the following four methods.

Table of contents

  • How to count Files in a directory
    • Example: Count Number Files in a directory
  • Count all files in the directory and its subdirectories
  • scandir() to count all files in the directory
  • fnmatch module to count all files in the directory

How to count Files in a directory

Getting a count of files of a directory is easy as pie! Use the listdir() and isfile() functions of an os module to count the number of files of a directory. Here are the steps.

  1. Import os module

    The os module provides many functions for interacting with the operating system. Using the os module, we can perform many file-related operations such as moving, copying, renaming, and deleting files.

  2. create a counter variable

    Set counter to zero. This counter variable contains how many files are present in a directory.

  3. Use os.listdir() function

    The os.listdir('path') function returns a list of files and directories present in the given directory.

  4. Iterate the result

    Use for loop to Iterate the entries returned by the listdir() function. Using for loop we will iterate each entry returned by the listdir() function.

  5. Use isfile() function and increment counter by 1

    In each loop iteration, use the os.path.isfile('path') function to check whether the current entry is a file or directory. If it is a file, increment the counter by 1.

Example: Count Number Files in a directory

The ‘account’ folder present on my system has three files. Let’s see how to print the count of files.

import os

# folder path
dir_path = r'E:\account'
count = 0
# Iterate directory
for path in os.listdir(dir_path):
    # check if current path is a file
    if os.path.isfile(os.path.join(dir_path, path)):
        count += 1
print('File count:', count)

Output:

File count: 3

A compact version of the above code using a list comprehension.

import os

dir_path = r'E:\demos\files_demos\account'
print(len([entry for entry in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, entry))]))

Count all files in the directory and its subdirectories

Sometimes we need to count files present in subdirectories too. In such cases, we need to use the recursive function to iterate each directory recursively to count files present in it until no further sub-directories are available from the specified directory.

The os.walk() Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at the directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).

For example, calling the os.walk('path') will yield two lists for each directory it visits. The first list contains files, and the second list includes directories.

Let’s see how to use the os.walk() to count files present in a directory and its subdirectories.

Example:

The ‘account’ folder on my system contains three files and one subdirectory containing one file. so we must get a 4 as the final count.

import os

count = 0
for root_dir, cur_dir, files in os.walk(r'E:\account'):
    count += len(files)
print('file count:', count)

Output:

file count: 4

scandir() to count all files in the directory

The scandir() function of an os module returns an iterator of os.DirEntry objects corresponding to the entries in the directory.

  • Use the os.scadir() function to get the names of both directories and files present in a given directory.
  • Next, iterate the result returned by the scandir() function using a for loop
  • Next, In each iteration of a loop, use the isfile() function to check if it is a file or directory. if yes increment the counter by 1

Note: If you need file attribute information along with the count, using the scandir() instead of listdir() can significantly increase code performance because os.DirEntry objects expose this information if the operating system provides it when scanning a directory.

Example:

import os

count = 0
dir_path = r'E:\account'
for path in os.scandir(dir_path):
    if path.is_file():
        count += 1
print('file count:', count)

Output:

file count: 3

fnmatch module to count all files in the directory

The fnmatch supports pattern matching, and it is faster.

  • For example, we can use fnmatch to find files that match the pattern *.* The * is a wildcard which means any name. So *.* indicates any file name with any extension, nothing but all files.
  • Next, we will use the filter() method to separate files returned by the listdir() function using the above pattern
  • In the end, we will count files using the len() function

Example:

import fnmatch

dir_path = r'E:\demos\files_demos\account'
count = len(fnmatch.filter(os.listdir(dir_path), '*.*'))
print('File Count:', count)

Output:

File Count: 3

Filed Under: Python, Python File Handling

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!

Related Tutorial Topics:

Python Python File Handling

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ
Exercises
Quizzes

Posted In

Python Python File Handling
TweetF  sharein  shareP  Pin

Python File Handling

  • File Handling In Python
  • Create File in Python
  • Open a File in Python
  • Read File in Python
  • Write to File in Python
  • Python File Seek
  • Rename Files in Python
  • Delete Files in Python
  • Copy Files in Python
  • Move Files in Python
  • List Files in a Directory
  • File Handling Quiz

All Python Topics

Python Basics Python Exercises Python Quizzes Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use, Cookie Policy, and Privacy Policy.

Copyright © 2018–2023 pynative.com