How to list all the files in a folder

1 min

One extremely useful code snippet I often use is how to list all the files in a folder.

Here is how to list all the files in a folder using the os library.

import os

# List the files in a folder
all_files = [each for each in os.listdir("./data/") if os.path.isfile(f"./data/{each}")]

You usually use it to loop over the files you want to work on.

I personally use this the most when I want to create a big DataFrame over a list of CSV files.

Here you are! You now know how to list all the files in a folder.

More on DataFrames

If you want to know more about DataFrame and Pandas. Check out the other articles I wrote on the topic, just here :

Pandas - The Python You Need
We gathered the only Python essentials that you will probably ever need.