Python list files in directory

Python can be used to automate work with files. In this notebook, we will show different ways to list files in the directory with Python. You can exclude directories from list and filter files by extension.

This notebook was created with MLJAR Studio

MLJAR Studio is Python code editior with interactive code recipes and local AI assistant.
You have code recipes UI displayed at the top of code cells.

Documentation

Here is the documents directory tree view that will be used in this notebook:

documents/
├── music
│   ├── bass-guitar-sample.mp3
│   ├── first-song.mp3
│   ├── italo-disco.mp3
│   └── rave.wav
├── my-cv.pdf
├── phd-thesis.txt
├── todo.txt
└── video
    ├── holidays-2023.mp4
    ├── holidays-2024.mp4
    └── zoo.mov
# import packages
from os import listdir
from os.path import isfile, join

List all files and directories from documents. Directories are treated as files in the file system. In Unix systems (Linux, macOS) everything is a file.

# list files in directory
my_files = [f for f in listdir("/home/piotr/documents")]
print("Files in directory /home/piotr/documents")
print(my_files)

List all files from documents/music.

# list files in directory
my_files = [f for f in listdir("/home/piotr/documents/music")]
print("Files in directory /home/piotr/documents/music")
print(my_files)

List all files from documents/video.

# list files in directory
my_files = [f for f in listdir("/home/piotr/documents/video")]
print("Files in directory /home/piotr/documents/video")
print(my_files)

Exclude directories from file list in documents.

# list files in directory
my_files = [f for f in listdir("/home/piotr/documents") if isfile(join("/home/piotr/documents", f))]
print("Files in directory /home/piotr/documents")
print(my_files)

Filter files with file extension.

# list files in directory
my_files = [f for f in listdir("/home/piotr/documents") if f.endswith("pdf")]
print("Files in directory /home/piotr/documents")
print(my_files)

Conclusions

Python is a great choice for working with files. You can easily list files in the selected directory. You can exclude directories from list. Filtering by file extension is possible.

Feel free to adapt above Python code recipes to your own needs. And remember, everything is a file!

Recipes used in the python-list-files-in-directory.ipynb

All code recipes used in this notebook are listed below. You can click them to check their documentation.

Packages used in the python-list-files-in-directory.ipynb

List of packages that need to be installed in your Python environment to run this notebook. Please note that MLJAR Studio automatically installs and imports required modules for you.