raton roguille
raton roguille

Reputation: 191

create dynamically dataframes

I have a set of csv files in a folder, and I would like to create dynamically dataframes having the same name as the csv file

for instance I have the following files : AC201703.csv AC201703.csv AC201704.csv I would like to load those file an put in dataframes having the same name e.g. AC201703 AC201704 I try to use exec like the following

for file in glob.glob("*.csv"):
   df = pd.read_csv(file,encoding = 'ISO-8859-1' )
   exec("%s = %s" % (file[:7],df)) 

but it didn't work, i get the following error

  File "<ipython-input-31-2d670638b427>", line 4, in <module>
    exec("%s = %s" % (file[:7],df))

  File "<string>", line 1
    A201610 =        A201610_fb_act_n_n_buy cust_key  A201610_fb_act_n_n LCELGST  \
                                                   ^
SyntaxError: invalid syntax

it seems to assign to the variable A201610 the name of csv columns

Upvotes: 0

Views: 115

Answers (1)

jezrael
jezrael

Reputation: 862511

I think better is use dict of DataFrames:

d = {file[:7] : pd.read_csv(file, encoding = 'ISO-8859-1') for file in glob.glob("*.csv")}

and then select DataFrame by keys - first 7 letters of filenames:

print (d['AC20170'])

But if dont want use dicts:

for file in glob.glob("*.csv"):
    globals()[file[:7]] = pd.read_csv(file,encoding = 'ISO-8859-1')

print (AC20170)

Upvotes: 3

Related Questions