How do I list all files of a directory?

Created by pycruftLinked to 86.9m issues across 160 teams

tl;dr

Here's how to list all files of a directory in Python.

The first method is to use the os.listdir() function. This function returns everything inside a directory, including files and directories.

The second method is to use os.path's isfile() function. This function can be used to only list files. To do this, you can use the following code:

from os import listdir from os.path import isfile, join onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]

The third method is to use os.walk(). This function yields two lists for each directory it visits - one for files and one for directories (dirs). To only list the top directory, you can use the following code:

from os import walk f = [] for (dirpath, dirnames, filenames) in walk(mypath): f.extend(filenames) break

Alternatively, you can use the following shorter code:

from os import walk filenames = next(walk(mypath), (None, None, []))[2] # [] if no file