04-Nov-2022
.
Admin
Hi Dev,
In this tutorial we will go over the demonstration of Get All Files from Directory in Python Code Example. you'll learn How to List All Files From a Directory in Python. you can see How to Get All Files From Directory in Python. This article will give you simple example of How to Get All Files From Folder in Python. Let's see bellow example Python Get All Files in Directory Example.
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.
so let's see following examples 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']
#Python