Search code examples
pythonpython-3.xfor-loopglobal-variablesglobal

Access multiple dynamic variables outside for loop - Global keyword in Python


I am using a for loop to read multiple csv files and create dataframe.I would like to access these data frames outside for loop as well. For which I used the Global keyword as well but it doesn't work.

for file in os.listdir('C:\\Users\\ABCDE\\Desktop\\Measurement'):
  if file.endswith('.csv'):
     print(file)
     name = file[3:6]
     global df_name   # this is the line 
     df_name = 'df' + name  
     print(df_name)
     df_name = pd.read_csv('C:\\Users\\ABCDE\\Desktop\\Measurement\\' + str(file),low_memory = False)
     df_name.rename(columns={0:'values'}, 
             inplace=True)       
     g = df_name.level_1.str[-2:] # Extracting column names
     df_name['lvl'] = df_name.level_1.apply(lambda x: int(''.join(filter(str.isdigit, x))))

As you can see above, I would like to access these dataframes (df_name (3 dataframes as I have 3 files) outside for loop as well

How do I use Global keyword to make these dataframes accessible outside for loop?


Solution

  • After your clarification with comments, you can achieve what you want using a list or a dictionary.

    dataFrames = list()
    dataFrameDict = dict()
    
    for file in os.listdir('C:\\Users\\ABCDE\\Desktop\\Measurement'):
      if file.endswith('.csv'):
         print(file)
         name = file[3:6]
         df_name = pd.read_csv('C:\\Users\\ABCDE\\Desktop\\Measurement\\' + str(file),low_memory = False)
         df_name.rename(columns={0:'values'}, 
                 inplace=True)       
         g = df_name.level_1.str[-2:] # Extracting column names
         df_name['lvl'] = df_name.level_1.apply(lambda x: int(''.join(filter(str.isdigit, x))))
         # ADD TO A LIST
         dataFrames.append(df_name)
         # OR TO A DICT
         dataFramesDict[name] = df_name
    
    
    # How to Access
    
    # Index for 10 files would be 0-9
    index = 0
    dataFrames[index]
    
    # Name of the dataset you want to access
    name = "..."
    dataFrameDict[name]