How to List Files in a Directory in Python

In this tutorial, we are going to learn two different ways of listing files/folders that are inside a directory in Python.

 

The os Module

The Python os module has the listdir() function, which lists all folders and files in the path supplied. Let's try this out on the current working directory (where the Python script is located) by supplying a . (dot) as the first argument.

 

import os

cwd = os.listdir('.')

print(cwd)
['fil.txt', 'pandas_white.svg', 'download.py', 'env']

 

As is shown in the example above, we get a list of all files and folders in the directory.

 

If you want to get files in a different directory, supply its path, which could be relative to the Python script or a full path.

 

# up two directories:
os.listdir('../..')

# full path:
os.listdir('/path/to/dir')

 

Read more about navigating directories using the cd command.

 

List Files Only

If you only want to list files, not subdirectories, use the following:

 

files = [f for f in os.listdir('.') if os.path.isfile(f)]
for f in files:
   print(f)
file.txt
file2.txt
file3.zip

 

List all Matching Files with glob

The glob module has the iglob() function which can be used to list files in a directory. What makes it powerful is you can use Regular Expressions to match directories and files.

 

Let's say we wanted to list all the .txt files in the current directory. We could use iglob() like this:

 

import glob

cwd = list(glob.iglob('./*txt'))

print(cwd)
['./file.txt', './file2.txt']

 

Recursively Search Directories in Python

We can use the ** comand in the iglob() function to recursively search directories like this:

 

import glob

cwd = list(glob.iglob('/Users/john/websites/**/*txt', recursive=True))

print(cwd)
['./file.txt', './file2.txt']

 

Noterecursive=True must be supplied for this to work.

Related Tutorials

 thumbnail

Unzip Files in Python

June 30, 2021