How to get the list of CSV files contained in a folder in Python

1 min

You might end up one day in a situation that will require you to aggregate data.

By example, some sales reports for which you will probably need to do some comparative analysis between years/months.

and you'll end up with a folder full of CSV files.

In order to retrieve all those CSV files here is a method I used most of the time utilizing a list comprehension.

# Import the os library to read the content of a folder
import os

# Return a list of csv filename contained in my_directory
my_file_list = [each for each in os.listdir("my_directory") if each.endswith(".csv")]
Get the list of CSV files contained in a folder

Then you can iterate over this list, read the data and perform more specific operations.

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.