ItSolutionStuff.com

How to Get All Files from Directory in Python?

By Hardik Savani • October 30, 2023
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: Python
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

Python Delete Folder and Files Recursively Example

Read Now →

Python Delete Files with Specific Extension Example

Read Now →

Python Delete Directory if Exists Example

Read Now →

Python Delete File if Exists Example

Read Now →

Python Post Request with pem File Example

Read Now →

Python Post Request with Json File Example

Read Now →

Python Post Request with Basic Authentication Example

Read Now →

Python Post Request with Bearer Token Example

Read Now →

Python Copy File From one Directory to Another Example

Read Now →

Python Create Zip Archive from Directory Example

Read Now →

How to Check if Today is Tuesday or not in Python?

Read Now →

How to Get Current Hour in Python?

Read Now →