King Balloonion
King Balloonion

Reputation: 27

Read multiple csv files and store content as list referenced by different names

So I have code that basically does this:

def setup_list(file_name):
    for item in csv file:
        list = []
        list.append(item)

However, I want to be able to assign list a different name each time the function is run. For example list_one, list_two etc. How can I do this?

From comment:

The end goal is too have the contents of several csv files stored in a few lists with different names. The files contain birds, dates and location in the same file.

I have several files as users may have several bird lists they wish to make (one for birds seen in their county/state, another file for birds seen all over the world etc.)

Upvotes: 0

Views: 1092

Answers (2)

Patrick Artner
Patrick Artner

Reputation: 51633

To read multiple files and its content into lists:

Create data:

with open("birds1.txt","w") as f:
    f.write(f"""
Bird,Date,Location
Amsel,1.1.2018,Amerika
Drossel,2.1.2018,Alaska
Fink,3.1.2018,Pacific
""")

with open("birds2.txt","w") as f:
    f.write(f"""
Bird,Date,Location
Eagle,1.1.2018,Afrika
Milan,2.1.2018,Eurasia
AngryBird,3.1.2018,Rainbow Meadow
""")

Load data:

import csv

def load_into_dict(d,filename):
    with open(filename) as f:
        csv_reader = csv.reader(f)
        name = filename.split(".")[0] 
        d[name] = []
        for row in csv_reader:
            if row:
                d[name].append(row)

data = {}
for n in ["birds1.txt","birds2.txt"]:
    load_into_dict(data,n)

Usage of loaded data:

print(data)
print(data["birds1"][1])

Output:

{'birds1': [['Bird', 'Date', 'Location'],      ['Amsel', '1.1.2018', 'Amerika'], 
            ['Drossel', '2.1.2018', 'Alaska'], ['Fink', '3.1.2018', 'Pacific']], 
 'birds2': [['Bird', 'Date', 'Location'],      ['Eagle', '1.1.2018', 'Afrika'], 
            ['Milan', '2.1.2018', 'Eurasia'],  ['AngryBird', '3.1.2018', 'Rainbow Meadow']]}

['Amsel', '1.1.2018', 'Amerika']

Documentation:

Upvotes: 0

Bill Wang
Bill Wang

Reputation: 140

You could create a dictionary for the lists, with your desired name as the key and the list as the value

dictOfLists = {}

def setup_list(file_name, list_name):
    l = []
    for item in csv file:
        l.append(item)
    dictOfLists.update({list_name : l})

It's generally not practical or advisable to rename variables and should not be done in most cases.

Upvotes: 1

Related Questions