How to Get All Files from Directory in Python?

By Hardik Savani October 30, 2023 Category : Python

If you need to see example of python get all files from directory. I would like to show you python get list of files in directory with extension. We will look at example of python get all files in directory example. This post will give you simple example of how to get all files from folder in python.

In this example, we will get list of all files from directory using python. we will use "glob" and "walk" from "os" library to getting list of files recursively. so let's see below examples.

You can use these examples with python3 (Python 3) version.

let's see below simple example with output:

Example 1: List of All Files from Directory

Simply get all files from folder without recursively. we will get all files from "files" folder.

main.py

import os, glob
  
fileList = glob.glob('files/*.*')
  
print(fileList);

Output:

['files/test.txt', 'files/demo.png']

Example 2: List of All Files from Directory Recursively

Simply get all files from folder with recursively. we will get all files from "files" directory and subdirectories.

main.py

from os import walk
  
# folder path
dirPath = 'files'
  
# list to store files name
res = []
for (dirPath, dirName, fileName) in walk(dirPath):
    res.extend(fileName)
  
print(res)

Output:

['test.txt', 'demo.png', 'demo.txt']

I hope it can help you...

Tags :
Shares