关闭在另一个函数中打开的文件时如何消除 "name error"?

How do I eliminate "name error" when closing a file that I opened in another function?

W_A11,2000-02,移动平均值,59.66666667、50.92582302、68.40751031,伤害,数字,攻击,验证,整体流行,所有年龄,致命,

W_A11, 2001-03, 移动平均值, 60, 51.23477459, 68.76522541, 伤害, 数字, 攻击, 验证, 整体流行, 所有年龄, 致命,

W_A11, 2002-04, 移动平均值, 59, 50.30812505, 67.69187495, 伤害, 数字, 攻击, 验证, 整体流行, 所有年龄, 致命,

def append_to_datalist(): #Datalist should be called append_to_datafile0, 
                          #change that for the next program

       """Append_to_datalist (should be datafile) first wipes the outfile 
          clean then appends all read lines containing the
          same year specified in querydate() from the infile to the 
          outfile"""

    outfile = open("datalist.csv", "w") #these two lines are for resetting 
                                         #the file so it remains manageably 
                                         #small
    outfile.write('')                   #this is the second line
    outfile = open("datalist.csv", "a")
    next(infile)
# extract data
    for line in infile:
        linefromfile = line.strip('\n').split(',')
        tuple1 = tuple(linefromfile)
        outfile.write('\n' + str(tuple1))
    outfile.close()

def openfile_and_append_to_datalist():
    # input for file name
    filename = input(
    "Please enter the name of the file, including the file extension, from 
     which we will be extracting data"
    " ex)injury_statistics.txt ")

    # open infile
    infile = open(filename, "r")

    # append infile data to outfile
    append_to_datalist()

    # close infile
    infile.close()

openfile_and_append_to_datalist()

当我 运行 这个文件时它 运行 很好,直到它尝试关闭 infile,然后它 returns "name error 'infile' is not defined."

我不确定除了从 openfile_and_append_to_datalist() 中取消嵌套 append_to_datalist() 之外还能尝试什么,我尝试失败了。

我的问题说 infile 在另一个函数中打开的原因是因为 append_to_datalist() 使用 infile。

看起来问题不在于 closing infile,而在于它在 append_to_datalist() 函数中的使用。 NameError 异常告诉您 infile 未定义是正确的,因为在那个函数中,它 没有 定义。它只定义在openfile_and_append_to_datalist().

的范围内

为了从 append_to_datalist() 引用 infile,您需要将其作为函数参数传递。首先更改您的函数定义:

def append_to_datalist(infile):
    ...

然后调用函数时传infile

infile = open(filename, "r")
append_to_datalist(infile)
infile.close()