Python 试图检查文本文件中是否有单词字符串,我遇到了StopIteration错误。我不知道为什么(关闭)
以下是我正在尝试运行的函数:Python 试图检查文本文件中是否有单词字符串,我遇到了StopIteration错误。我不知道为什么(关闭),python,function,file-handling,Python,Function,File Handling,以下是我正在尝试运行的函数: def parsefile(file_name,d_name): with open(file_name) as fn: if "Station" in fn.read(): next(fn) for line in fn: (stat,north,east) = line.split() d_name[stat
def parsefile(file_name,d_name):
with open(file_name) as fn:
if "Station" in fn.read():
next(fn)
for line in fn:
(stat,north,east) = line.split()
d_name[stat] = (north,east)
else:
print("Please input correct file with header: Stations, Northings, Eastings")
return d_name
以下是我的文本文件的一个片段:
Station Northings Eastings
1 10001.00 10001.00
2 10070.09 10004.57
3 10105.80 10001.70
open(即fn)的结果是一个迭代器。迭代器使用next给出值,当迭代器耗尽时,将引发StopIteration。对于在里面构造和许多处理迭代器的函数将为您处理此异常
read读取整个文件,之后就没有什么可读取的了,有效地耗尽了迭代器;从fn请求下一个值将引发StopIteration。如果您想重新开始读取文件,可以使用fn.seek0倒带文件指针;但是,请注意,某些文件句柄不能被重绕,特别是标准输入。阅读所有内容后,您接下来会看到什么?谢谢!我明白为什么我不应该仅仅用fn.read。