Search code examples
pythonimportblobxlsx

Reading multiple files into separate data frames


I found this method on stack :

import glob
d = {}
for filename in glob.glob('*.xlsx'):
    d[filename[:-4]] = pd.read_excel(filename, sheet_name = 'Bilan')

How do I change that to have the name of all of my dataframe more like :

-df1

-df2

-df3

...

-dfN

and so on. The name based on the filename is nice but tedious to code with.


Solution

  • You can probably do something like this:

    import glob
    d = {}
    base_name = "df{}"
    flag = 0
    
    for filename in glob.glob('*.xlsx'):
        d[base_name.format(flag)] = pd.read_excel(filename, sheet_name = 'Bilan')
        flag += 1
    

    Here you create a base_name for your name and a flag to track the position of your file and then use those variables to construct a full filename.