0

I have a list 'filenames' which correspond to the .csv files I want to read.

filenames = ['filename_1', 'filename_2', ..., 'filename_n']

for file in filenames:
    file_address = '{}{}'.format(file, '.csv')
    file = pd.read_csv(file_address)
    display(file.info())

Desired outcome:
I would like to create a variable with the name corresponding to the file it read.

type(filename_1)
pandas.core.frame.DataFrame

I will appreciate it if you tell me how to Google it or if you can provide me an example of how to archive this.

Echo9k
  • 554
  • 6
  • 9
  • 1
    tl;dr since they're ordered, put them in a list – wjandrea Dec 28 '19 at 21:21
  • Why? I assume the list of filenames is dynamically created with `walk` or `listdir`. How will you handle dynamically created variable names? If it is not dynamically created, why not create separated variables to begin with? – DeepSpace Dec 28 '19 at 21:21
  • 3
    Other solution might be creating a `dict`, where keys are filenames and values are corresponding Dataframes. – Andrej Kesely Dec 28 '19 at 21:22

1 Answers1

1

If you want to reference the variable only for the duration of the loop:

import pandas as pd
for file in filenames:
    f = pd.read_csv(file + '.csv')
    print(f)

If you want to reference a variable for each file outside of the loop, use a dictionary:

  import pandas as pd
  d = dict()
  for count, file in enumerate(filenames):
      d['f' + str(count)] = pd.read_csv(file + '.cvs')

Then reference any filename by its key in the dictionary, e.g.: d['f1']

gregory
  • 10,969
  • 2
  • 30
  • 42