Python – Get list of files in directory

Get list of files in directory in Python

To get the list of files in a directory in Python,

  1. Import listdir from os, and import isfile, and join from os.path.
  2. Given a directory path.
  3. Get the list of files and directories in the given directory path using listdir(dir_path).
  4. For each item in the list returned by listdir(dir_path), check if the item is a file or directory. Consider the item if it is a file, or discard the item if it is not a file. You can check if item is a file or not using isfile() method.

If dir_path is the given directory path, then the statement to get the list of files at the directory path is

files = [file for file in listdir(dir_path) if isfile(join(dir_path, file))]
Copy

Examples

1. Get list of files in directory in Python

In the following program, we shall get the list of only files at the given directory path “data/directory1”, and print the list of files to standard output.

Python Program

from os import listdir
from os.path import isfile, join

dir_path = "data/directory1"
files = [file for file in listdir(dir_path) if isfile(join(dir_path, file))]

for file in files:
    print(file)
Copy

Output

Python - Get list of file in directory

Summary

In this tutorial of Python File Operations, we have seen how to get the list of files in a given directory path, with examples.

Related Tutorials

Code copied to clipboard successfully 👍