How do I list all files of a directory?

os.listdir() returns everything inside a directory — including both files and directories.

os.path‘s isfile() can be used to only list files:

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

Alternatively, os.walk() yields two lists for each directory it visits — one for files and one for dirs. If you only want the top directory you can break the first time it yields:

from os import walk

f = []
for (dirpath, dirnames, filenames) in walk(mypath):

or, shorter:

from os import walk

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

Leave a Comment