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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# import glob module import glob print("--------- Using Glob Module *") # Match all files that end with txt extension files = glob.glob('/Path/to/dir/*.txt') for fn in files: print(fn) print("count = {}".format(len(files))) # Lists all files that looks like (ex. 1.txt) print("--------- Using Glob Module ?") files = glob.glob('/Path/to/dir/?.txt') for fn in files: print(fn) print("count = {}".format(len(files))) |
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…
1 2 3 4 5 6 7 8 9 10 |
# os module is needed import os print("--------- Using os.listdir") n = 0 files = os.listdir('/Path/to/dir') for fn in files: if fn.endswith('.txt'): n += 1 print(fn) print("count = {}".format(n)) |
List comprehensions syntax
If you like elegant code, you may use list comprehensions with os.listdir. Take a look…
1 2 3 4 5 6 |
# os module is needed import os print("--------- Using list comprehensions") files = [fn for fn in os.listdir('/Path/to/dir/') if fn.endswith('.txt')] print(files) print("count = {}".format(len(files))) |
Using os.walk
If you want to recursively scan a directory for files and directories, you may use os.walk. Take a look…
1 2 3 4 5 6 7 8 9 |
# os module is needed import os print("--------- Using os.walk") n = 0 for r, d, files in os.walk('/Path/to/dir/'): n+= len(files) print(files) print("count = {}".format(n)) |
Summary
Here is a short summary of the Python syntax used…
Method | Syntax |
---|---|
glob module | glob.glob('/Path/to/dir/*.txt') |
os module listdir | os.listdir('/Path/to/dir') |
os module walk | os.walk('/Path/to/dir/') |
Thanks for visiting. For questions and feedback, please use the comments section below.