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)
错误:名称'LEVEL_001'未定义
我试图创建一个接收文件名+ listname的函数,从而从文件(filename)读取数据,并将其放在列表(listname)中。创建了一个列表,但没有正确的名称。有正确的方法吗?
字符串值'LEVEL_001'
与变量LEVEL_001
不是一回事。
不要试图将变量名作为参数传递给函数,你应该将你在函数中创建的值return
,然后在调用代码中为它分配一个变量名:
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)