# List All Files in a Directory in Python

This tutorial shows how to list files with an extension in a directory and its subdirectories. This is an example directory which consists of files and directories.

## Using a working directory

If you want to use the working directory, instead of the specified one, you can use the following code.

## List all files and directories in the directory non-recursively

This code will get all filenames + extensions and directories from the directory without entering other directories that are inside this one.

And this is the output:

['data', 'pic1.jpg', 'pic2.jpg', 'pic3.jpg', 'text', 'text.txt']

It may be useful if you want to create a program that will print the current directory tree. If you write such a script, you can then convert it to a single exe file.

## List only files in the directory non-recursively

In the previous example, both, files and directories are listed.

Let’s display only files.

output

['pic1.jpg', 'pic2.jpg', 'pic3.jpg', 'text.txt']

## List all files recursively (directory and subdirectories)

In order to list all files in the directory and its subdirectories, we will use os.walk. It will check each directory recursively and display all files.

output

['pic1.jpg', 'pic2.jpg', 'pic3.jpg', 'text.txt', 'data.txt', 'data.xlsx', 'simple text.docx']

## List all files and directories recursively (directory and subdirectories)

output

['pic1.jpg', 'pic2.jpg', 'pic3.jpg', 'text.txt', 'data.txt', 'data.xlsx', 'simple text.docx', 'data', 'text', 'spreadsheet', 'notepad', 'word']

## List all files recursively using a wildcard and display the full path

So far, we were displaying only files and directories names. This time let’s display the full path. The wildcard (*.*) means that it displays all types of files.

output

['D:\\mydir\\pic1.jpg', 'D:\\mydir\\pic2.jpg', 'D:\\mydir\\pic3.jpg', 'D:\\mydir\\text.txt', 'D:\\mydir\\data\\data.txt', 'D:\\mydir\\data\\spreadsheet\\data.xlsx', 'D:\\mydir\\text\\word\\simple text.docx']

## List all files recursively with a specific type of file

You can also display only one type of file. Let’s display only text files. Change (*.*) to (*.txt).

And this is the output.

['D:\\mydir\\text.txt', 'D:\\mydir\\data\\data.txt']

## List all files and directories recursively and display the full path

Only a slight modification (*.* >> *) in the script to display both files and directories.