名称错误:未定义名称“enddata”(函数内部)

2024-10-02 16:32:52 发布

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

当我试图运行它时,它说“enddata”没有定义,即使它是一个包含文档中格式化数据的列表。有没有更好的编码方法?你知道吗

def openfile ():

    global enddata
    global index

    file=open("weatherData.csv","r")
    data=file.readlines()
    file.close()

    enddata=[]
    index=0

    for sample in data:
        enddata.append(data[index].split(","))
        index +=1

    print("-"*50)

    return enddata

print(enddata)

Tags: 数据文档列表dataindex定义defopen
3条回答

这是一种更高级的代码编写方法。你知道吗

  • 我使用with statement so that I don't have to remember to close the file. It makes the code more compact in general.weatherData`作为文件的别名。你知道吗
  • sample成为输入文件中一行的名称。你知道吗
  • 需要注意的是,文件中的每一行都有一个所谓的“行尾”,必须去掉它;因此.strip()。然后我可以在逗号上做.split。你知道吗
  • 因为每个输入行可以包含多个值,所以我使用.extend将它们添加到enddata。你知道吗
  • 我写了print (openfile())来看看结果。或者我可以写result = openfile(); print(result)。你知道吗

是的。你知道吗

def openfile():
    enddata = []
    with open('weatherData.csv') as weatherData:
        for sample in weatherData.readlines():
            enddata.extend(sample.strip().split(','))
    return enddata

print (openfile())

输出:

['1', '2', '3', '4', '5', '6']

正如其他人指出的,您必须调用openfile函数:代码可以如下所示:

def openfile ():

    global enddata
    global index

    file=open("weatherData.csv","r")
    data=file.readlines()
    file.close()

    enddata=[]
    index=0

    for sample in data:
        enddata.append(data[index].split(","))
        index +=1

    print("-"*50)

    return enddata

openfile()
print(enddata)

另一种更简短的方法是:

def openfile():
    with open("weatherData.csv") as f:
        return [line.split(',') for line in f]

enddata = openfile()
print("-"*50)
print(enddata)

值得探索csvPython模块:

import csv

def openfile():
    with open('weatherData.csv') as f:
        return list(csv.reader(f))

enddata = openfile()
print("-"*50)
print(enddata)

您必须调用openfile,它才能初始化(并为此创建)全局名称enddata。但是,不应使用全局变量。让openfile返回要赋给enddata的值,并将其赋给调用范围中的变量。你知道吗

其他一些提示:

  • 你的函数不只是打开一个文件,它读取它并返回一些数据。你知道吗
  • 使用with语句管理打开和关闭文件。你知道吗
  • 不要一次把整个文件读入内存,要逐行读。你知道吗
  • 在某种意义上,您在data上迭代了两次:一次使用for循环,另一次使用index。似乎在每次迭代中sample == data[index]。整个迭代可以用一个列表来处理。你知道吗
  • 使用csv模块读取CSV文件。你知道吗

综合起来:

import csv

def read_file(fname):
    with open(fname) as fh:
        return list(csv.reader(fh))

enddata = read_file("weatherData.csv")

相关问题 更多 >