How To List Every File in a Directory in Python

Use the ‘os’ library and filter() function

How To List Every File in a Directory in Python
Photo by Goran Ivos on Unsplash

Traversing local file storage is a handy skill to have. Working within the local system, the os library will be your friend. There are multiple strategies within os that can be used to retrieve all files in a directory.

In this tutorial, we’ll use the listdir() function and manipulate the results to return only files.


Import the Starting Libraries

To get started, we need three methods from the os library.

  • listdir: Retrieve the contents—both directories and files—of a directory.
  • join: Combine two components into a single path.
  • isfile: Returns true if the given path component is a file.from os import listdir
    from os.path import join, isfile

Retrieving the Contents of the Directory

After importing the necessary methods, it’s time to set the path to the directory and retrieve its contents.from os import listdir
from os.path import join, isfiledirectory_path = "/some/path"
contents = listdir(directory_path)


Filter Out Directories

Now that we have all the contents of the directory, it’s time to filter out the directories—leaving only the files.from os import listdir
from os.path import join, isfiledirectory_path = "/some/path"
contents = listdir(directory_path)files = filter(lambda f: isfile(join(directory_path,f)),contents)

The filter() function takes two arguments: a function that determines if the item will be included and the sequence to be filtered. We use a lambda expression to determine if the joined path and directory content is a file. It’s important to remember that filter() will return a filter object, and so you should convert files to a list in order to print the contents.from os import listdir
from os.path import join, isfiledirectory_path = "/Users/jhsu/Desktop"contents = listdir(directory_path)files = filter(lambda f: isfile(join(directory_path,f)),contents)print(files) # <filter object at 0x10a5203a0>
print(list(files)) # [list of files]

Subscribe to Dreams of Fortunes and Cookies

Sign up now to get access to the library of members-only issues.
Jamie Larson
Subscribe