当我试图运行它时,它说“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)
这是一种更高级的代码编写方法。你知道吗
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)
。你知道吗是的。你知道吗
输出:
正如其他人指出的,您必须调用
openfile
函数:代码可以如下所示:另一种更简短的方法是:
值得探索csvPython模块:
您必须调用
openfile
,它才能初始化(并为此创建)全局名称enddata
。但是,不应使用全局变量。让openfile
返回要赋给enddata
的值,并将其赋给调用范围中的变量。你知道吗其他一些提示:
with
语句管理打开和关闭文件。你知道吗data
上迭代了两次:一次使用for
循环,另一次使用index
。似乎在每次迭代中sample == data[index]
。整个迭代可以用一个列表来处理。你知道吗csv
模块读取CSV文件。你知道吗综合起来:
相关问题 更多 >
编程相关推荐