Coding Triumph

Helpful code snippets & tutorials

How to list all files and subfolders in a directory with Python

In Python, you can easily list all files and subdirectories in a given directory with the listdir() from the built-in os module. Let’s find out how to achieve that.

First thing first, this is the structure of the directory we’ll be working with:

./
|__ ./subfolder1
|__ ./subfolder1
|__ ./subfolder3
|
|__ file1.txt
|__ file2.txt
|__ file3.txt
|__ main.py

1. Listing all files and subfolders in a directory:

import os

# list files and subfolders in the current directory
all = os.listdir('./')
print(all) # ['main.py', 'file1.txt', 'subfolder3', 'subfolder2', 'file3.txt', 'subfolder1', 'file2.txt']

2. List only the files in a directory:

import os

# list of all files and subfolders
all = os.listdir('./')

# filter the files only
files = list(filter(lambda file: os.path.isfile(file), all))
print(files) # ['main.py', 'file1.txt', 'file3.txt', 'file2.txt']

3. List only subfolders in a directory:

import os

# list of all files and subfolders
all = os.listdir('./')

# filter the files only
dirs = list(filter(lambda dir: os.path.isfile(dir), all))
print(files) # ['subfolder3', 'subfolder2', 'subfolder1']

Conclusion:

That’s all. With the help of listdir(), we were able to get a list of all files and subdirectories in a folder with Python. I hope you find this post helpful.

If you like this post, please share
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments