List directory file names and count in Python

Introduction

Given a directory path on the file system, the following Python code snippets retrieve a list of file names and total count using different methods. You may use the one that best suite your needs or find it more elegant. Let us get started…

Using glob module

In this example, we are going to use the glob module to retrieve all text files in a given directory. The glob module allows us to scan files using regular expression syntax which is a very powerful technique. This technique provides full path file names along with file count:

Using os module

We can manually find file count in a directory using os.listdir. In this case, only file name (not full path) is printed. Let us see how…

List comprehensions syntax

If you like elegant code, you may use list comprehensions with os.listdir. Take a look…

Using os.walk

If you want to recursively scan a directory for files and directories, you may use os.walk. Take a look…

Summary

Here is a short summary of the Python syntax used…

MethodSyntax
glob moduleglob.glob('/Path/to/dir/*.txt')
os module listdiros.listdir('/Path/to/dir')
os module walkos.walk('/Path/to/dir/')

Thanks for visiting. For questions and feedback, please use the comments section below.

Tags:

Add a Comment

Your email address will not be published. Required fields are marked *