Listing all files in a directory in Python

There are 2 ways of doing this: using os.listdir(), or using os.walk().

Use os.listdir()

os.listdir() will give you files and directories. You can filter them with a list comprehension as follows:

import os
import os.path

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

Use os.walk()

os.walk() separates files and directories, and will recurse into directories. To get only the files in the current directory, just save the third element of the tuple and break out of the loop:

import os

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