How To List All Files Of A Directory In Python?

Files are used to store different types of data. While working with the Python programming language we may need to list specified directory files. There are different methods to list all files of a directory in Python.

List All Files of a Directory with listdir() Method

The listdir() method is provided via the os module. In order to use the listdir() method we will first import the os module and than call the listdir() method by providing the path or directory we want to list all folders. In the following example we will list all files for the “/home/ismail” directory.

from os import listdir
from os.path import isfile, join

path = "/home/ismail"

files = [file for file in listdir(path) if isfile(join(path, file))]

The listdir() method returns a list type where every file and folder is listed. We use the isfile() method from the os.path module to check if the list item is a file or not.

List All Files of a Directory with glob() Method

Another way to list all files in a directory is the glob() method which is provided via the glob module. The directory path is provided into the glob() method. We will specify the path with the glob sign like “/home/ismail/*” which means all files and folders under the “/home/ismail“.

import glob 

path = "/home/ismail/*"

files = [file for file in glob.glob(path) if isfile(join(path, file))]

Leave a Comment