-1
import csv

def readLevel(filename,listname):
    listname=[]
    with open(filename, "r") as element:
        csv_reader = csv.reader(element)
        listname = list(csv_reader)

readLevel('level001.csv','LEVEL_001')
readLevel('level002.csv','LEVEL_002')

print(LEVEL_001)
print(LEVEL_002)

Error: name 'LEVEL_001' is not defined

I'm trying to create a function that receives a filename + listname and thus reads the data from a file (filename) and put it in a list (listname). A list is created but not with the correct name. Is there a correct way to do this ?

Rabbid76
  • 202,892
  • 27
  • 131
  • 174

1 Answers1

1

The string value 'LEVEL_001' is not the same thing as a variable called LEVEL_001.

Instead of trying to pass a variable name as an argument to the function, you should return the value that you create in your function and then assign it a variable name in the calling code:

import csv

def readLevel(filename):
    with open(filename, "r") as element:
        return list(csv.reader(element))


LEVEL_001 = readLevel('level001.csv')
LEVEL_002 = readLevel('level002.csv')

print(LEVEL_001)
print(LEVEL_002)
Samwise
  • 68,105
  • 3
  • 30
  • 44