Carson Yau
Carson Yau

Reputation: 519

How can i read multile csv files at once at python?

df1 =  pd.read_table('CUSR0000SS62031.csv', sep=',')
df2 =  pd.read_table('CUUR0000SS62031.csv', sep=',')
df3 =  pd.read_table('CUSR0000SERA02.csv', sep=',')
df4 =  pd.read_table('CUUR0000SERA02.csv', sep=',')
df5 =  pd.read_table('CUUR0000SEFR02.csv', sep=',')

Now I am writing codes like this in order to load the csv files....but it takes time to produce codes...

If I have an array of the filenames, can I automate the above codes with a while/for loop? Thanks so much, I have tried but not sure how to also change the name of the df1 to n automatically...Thanks!!

Upvotes: 1

Views: 61

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140256

Generating variable names is not a good idea, but as a nice alternative, you could create your dataframes in a list comprehension:

df_list = [pd.read_table(f,sep=',') for f in ['CUSR0000SS62031.csv','CUUR0000SS62031.csv','CUSR0000SERA02.csv','CUUR0000SERA02.csv','CUUR0000SEFR02.csv']]

then access your dataframes by index (ex: df_list[1]) or in a loop:

for dfx in df_list:
   # do something with dfx pd.dataframe object

Upvotes: 2

Related Questions