关闭在另一个函数中打开的文件时,如何消除“名称错误”?​​

时间:2019-02-20 14:58:30

标签: python-3.x function fclose

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,然后它返回“未定义名称错误'infile'”。

除了不确定我尝试失败的openfile_and_append_to_datalist()的append_to_datalist()嵌套之外,我不确定要尝试什么。

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

1 个答案:

答案 0 :(得分:2)

问题似乎不在于结束 infile,而在于它在append_to_datalist()函数中的使用。告诉您NameError未定义的情况是正确的infile,因为在该函数中未定义{em> 。仅在openfile_and_append_to_datalist()的范围内定义。

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

def append_to_datalist(infile):
    ...

然后在调用函数时传递infile

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