0

I am trying to read in 12 separate CSV files and would like to use a for loop to do it. For some reason the code doesn't seem to be working:

files = ['Jan2016', 'Feb2016', 'Mar2016', 'Apr2016', 'May2016', 'Jun2016', 'Jul2016', 'Aug2016', 'Sep2016', 'Oct2016', 'Nov2016', 'Dec2016']

for file in files: 
    file = pd.read_csv("/Volumes/Toshiba/PrescriptionData/Results2/" + i + ".csv")

print(Jan2016)

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-49-906109eb8ce9> in <module>()
      4     file = pd.read_csv("/Volumes/Toshiba/PrescriptionData/Results2/" + i + ".csv")
      5 
----> 6 print(Jan2016)

NameError: name 'Jan2016' is not defined

However, when I enter print(file) the code compiles and prints the data from the Dec2016 CSV file (i.e the final value in my 'files' list). Any ideas on why this for loop is not working?

Vishal
  • 5
  • 2

1 Answers1

0

You need dict comprehension for dictionary of DataFrames:

path = "/Volumes/Toshiba/PrescriptionData/Results2/"
dfs = {file : pd.read_csv(path + file + ".csv") for file in files}

What is same as:

dfs = {}
path = "/Volumes/Toshiba/PrescriptionData/Results2/"
for file in files: 
    dfs[file] = pd.read_csv(path + file + ".csv")

And then select in dictionary by keys:

print (dfs['Jan2016'])
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • Thanks for the prompt reply, unfortunately it still gives me the same problem – Vishal Jan 08 '18 at 10:02
  • @Vishal tell me `"one" = 100` does this make sense. This is what is happening in your loop. – Bharath M Shetty Jan 08 '18 at 10:05
  • @Vishal - Can you explain more? What does not work? – jezrael Jan 08 '18 at 10:06
  • @jezrael hes trying to create variables using for loop. – Bharath M Shetty Jan 08 '18 at 10:07
  • @Dark - yes that makes sense to me, what I'm trying to do is one=100, which according to me should work? – Vishal Jan 08 '18 at 10:21
  • @jezrael apologies, I didn't see the code you put below the first 2 lines. I will try that, however I'm wondering whether by using a dictionary to store the data, I can use pandas functions like dataframe concatenation, which is what I would like to do with the 12 data frames – Vishal Jan 08 '18 at 10:23
  • Dude `"one"` is different than `one`. For loop doesn't serve you fresh variables instead they serve the strings present in the list. Tell me the language you know complete basics of I will explain with the help of that. Things in programming language wont work according to one's wish it works according to fundamental principle. – Bharath M Shetty Jan 08 '18 at 10:23
  • @Vishal - each value in dict is normal `DataFrame`, so is possible use `df = pd.concat(dfs)` as next step – jezrael Jan 08 '18 at 10:26
  • @jezrael Thank you! that works perfectly – Vishal Jan 08 '18 at 10:38