List Files in a Directory in Python

Python provides an easy way to create and delete files & folders. In this tutorial, we will cover how to perform one of the most common task: list all files in a directory.

To better understand our codes, we’ll assume that our directory is the following one:

Use os.listdir() to list files in a directory

os.listdir() method is undoubtedly the simplest way to achieve our objective. It will list all files for a given directory. Some important notes:

  • This method returns a list of files
  • If no parameter is indicated, it will return the files & directories located in the folder where your Python file is located
  • It does not return files & folders beyond the first level
  • It returns only file names, not the full path

If we execute the following code from file.py:

import os files = '\n'.join(os.listdir()) print(files)
Code language: Python (python)

By default, os will return files and directories. If you want to keep files only, make sure that you use the os.path.isfile() method:

import os files = '\n'.join([file for file in os.listdir() if os.path.isfile(file)]) print(files)
Code language: Python (python)

Output:

oktoberfest-munich-biere-istock.jpg oktoberfest-munich-istock.jpg oktoberfest-munich-toilettes-istock.jpg file.py
Code language: CSS (css)

If you need to keep only files with a given extension, you just have to add a simple if statement to your code:

import os files = '\n'.join([file for file in os.listdir() if '.jpg' in file]) print(files)
Code language: Python (python)

Output:

oktoberfest-munich-biere-istock.jpg oktoberfest-munich-istock.jpg oktoberfest-munich-toilettes-istock.jpg
Code language: CSS (css)

Use glob to list files in a directory

In some cases, you may want to prefer glob over the os module. The main differences between the two are the following:

  • It supports pattern matching, which allows you to simplify your code
  • It returns a list of files with the full path. You do not need to build it yourself if you need to read or write these files afterwards
  • You have to specify a folder as the (only) parameter.

The following code will return only .jpg files in our folder for instance:

import glob files = '\n'.join(glob.glob('/Users/xxx/Downloads/iloveimg-resized (1)/*.jpg')) print(files)
Code language: Python (python)

Output:

oktoberfest-munich-biere-istock.jpg oktoberfest-munich-istock.jpg oktoberfest-munich-toilettes-istock.jpg
Code language: CSS (css)

Leave a Reply

Your email address will not be published. Required fields are marked *