如何在python中将文件路径设置为全局变量?

2024-05-31 23:32:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直收到这个错误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()

Tags: toconvertstring错误notgloballistreader
2条回答

这里不需要全局变量,函数应该接受路径作为参数并返回菜单列表

import csv

def menu_List(filep):

    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])
    return menulist

menulist = menu_List("a/path/goes/here")

与您的问题无关,您可以像这样跳过标题:

reader = f.readlines()
for row in reader[1:]: # skip the first line.
    ...

上面的答案(对fliep使用args)是最好的解决方案,但如果您决定不使用args:

filep= 'file path you want'# filepath
menulist = [] #global scope


def menu_List():
    global filep #just add one more global will make it work
    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()

额外小贴士:尽可能避免使用全局变量,全局变量会降低程序的速度并消耗内存,有时还会导致变量命名混乱

相关问题 更多 >