List All Files from Directory and Subdirectory in Python Example

Sovary October 13, 2022 430
1 minute read

This tutorial demonstrates getting all files from a directory with a Python code example. For someone looking for how to list all files from a directory in Python this is correct place to see with short example. You will understand how to show all files in a directory with Python programming. The given example below of how to get list all files from folder directory in Python. So let's see below sample example in Python getting all files in sub-directory with sample output.

Example #1 - List of All Files in Directory

The below code to list all files in current directory without recursively in sub-directory.

Create file main.py

import os, glob

files = glob.glob('folder/*.*')
print(files);

Output #1

['folder/my_noted.txt', 'folder/meme.jpeg', 'folder/tutorial.docx']

Example #2 - List All Files in Sub-Directory Recursively

Suppose we have directory named "folder"  and in that directory have files and other directories as well, in this case we will recursivly walkthrought all subdirectories to find all files.

Create file main.py

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

print(files )

Output #2

['my_noted.txt', 'meme.jpeg', 'tutorial.docx', 'demo.png']

Hope you can understand and know how to get list file in directories. Have a nice day!!

You may also like...

 

Python 
Author

Founder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him