Python Get All Files from Directory Example

Hi Guys,
In this tutorial, we will explore how to retrieve all files from a directory using Python. You will learn different ways to list files, including recursive search through subdirectories. We will cover the use of Python's built-in "os" and "glob" modules to accomplish this task efficiently.
Whether you need to scan a single folder or search within subdirectories, this guide provides a step-by-step approach with clear examples. Let’s dive in!
Example 1: Get All Files from a Directory
This example demonstrates how to retrieve all files from a specific folder without searching subdirectories.
main.pyimport glob fileList = glob.glob('files/*.*') print(fileList);Output
['files/test.txt', 'files/demo.png']
Example 2: Get All Files from Directory Recursively
If you need to list all files including those inside subdirectories, use the os.walk() function.
main.pyimport os # Define folder path dirPath = 'files' # List to store file names res = [] for (root, dirs, files) in os.walk(dirPath): for file in files: res.append(os.path.join(root, file)) print(res)Output
['files/test.txt', 'files/demo.png', 'files/subfolder/demo.txt']
Frequently Asked Questions (FAQ)
1. How do I get all files in a directory using Python?You can use the glob module to retrieve all files from a folder:
import glob files = glob.glob('files/*.*') print(files)2. How do I list all files in a directory and its subdirectories?
You can use os.walk() to retrieve files recursively:
import os for root, dirs, files in os.walk('files'): for file in files: print(os.path.join(root, file))3. Can I filter files by extension?
Yes! You can use glob to filter specific file types:
import glob files = glob.glob('files/*.txt') print(files)4. How to count the number of files in a directory?
You can count files using len() with glob:
import glob count = len(glob.glob('files/*.*')) print(count)5. How do I check if a folder contains files in Python?
Use os.listdir() to check if a directory contains files:
import os if os.listdir('files'): print("Folder is not empty") else: print("Folder is empty")
Hope this helps! Happy Pythonic Coding! 🚀