Search code examples
pythonpandascsvglob

Sorting files using glob


I am trying to read a bunch of csv files using glob in python. I want to read all the files in ascending order and then assign the data from each file to a different array.

My code right now looks like this:

for idx, f in enumerate (glob.glob(os.path.join(gen_path, "*.csv"))):
    data[idx] = pd.read_csv(f, index_col=False)

Can anyone help read the files in a sorted way.

Thanks.


Solution

  • glob returns a list of strings. Just sort it.

    for idx, f in enumerate(sorted(glob.glob(os.path.join(gen_path,"*.csv")))):