2

I am trying to import n tables with a loop, giving a different name for each table.

I can write the code to import the tables but I can't give a different name for each table:

  1. the path to find the files (csv)

    totalbaseURL=('path')
    
  2. find all the csv files

    folders = os.listdir(totalbaseURL)
    

    i.e., folders becomes ["house","cars","food","pubs"].

  3. folders contains the name of the csv files

    for f in folders:        
        path=totalbaseURL+f
        table=pd.read_csv(path,delimiter=';')
    

How could I put, instead of "table"? I would like to use the names in folders: (house, cars, food, pubs).

1
  • 1
    To associate strings with values, use a dictionary. Commented Jun 5, 2018 at 16:25

3 Answers 3

2

Use a dict,

folders=["house","cars","food","pubs"]

di = {}

for f in folders:        
    path=totalbaseURL+f
    di[f]=pd.read_csv(path,delimiter=';')
Sign up to request clarification or add additional context in comments.

Comments

0

U can use a dict to achieve it:

dataframe_dict = {}
totalbaseURL=('path')
folders = os.listdir(totalbaseURL)
for f in folders:
    path=totalbaseURL+f
    dataframe_dict[f]=pd.read_csv(path,delimiter=';')
print dataframe_dict

Output:

{"house": DataFrame1, "cars": DataFrame2, "food": DataFrame3, "pubs": DataFrame4}

Comments

0
import os
for f in folders:        
    path = os.path.join(totalbaseURL, f)
    globals()[f] = pd.read_csv(path, delimiter=';')

This will create global variables house, cars, food, and pubs. If this code is inside a function, use locals() instead of globals().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.