我一直收到这个错误NameError: name 'filep' is not defined
我需要将filep作为文件路径。但每次我运行我的代码,我总是得到这个错误
我需要将filep作为模块变量,而不是参数和menulist
import csv
filep= # filepath
menulist = [] #global scope
def menu_List():
global menulist
menulist = [] # store items
try:
with open(filep) as f: # read file
reader = f.readlines()
next(reader, None) #skip the header
for row in reader:
row[2] = int(row[2].strip()) #convert string to int
row[1] = float(row[1].strip()) #convert string to float
if row[2] > 100 and row[2] < 200:
menulist.append(row)
except NameError:
raise ValueError("Variable not set")
menulist.sort(key=lambda x: x[-1])
menu_List()
这里不需要全局变量,函数应该接受路径作为参数并返回菜单列表
与您的问题无关,您可以像这样跳过标题:
上面的答案(对fliep使用args)是最好的解决方案,但如果您决定不使用args:
额外小贴士:尽可能避免使用全局变量,全局变量会降低程序的速度并消耗内存,有时还会导致变量命名混乱
相关问题 更多 >
编程相关推荐