我已經編寫了一個迭代器類,用於打開文件__init__
。Python自定義迭代器:關閉StopIteration上的文件
def __init__(self, path):
self.file = open(path, "r")
如何在迭代完成後自動關閉該文件?
完整的類:
class Parse(object):
"""A generator that iterates through a CC-CEDICT formatted file, returning
a tuple of parsed results (Traditional, Simplified, Pinyin, English)"""
def __init__(self, path):
self.file = open(path, "r")
def __iter__(self):
return self
def __is_comment(self, line):
return line.startswith("#")
def next(self):
#This block ignores comments.
line = self.file.readline()
while line and self.__is_comment(line):
line = self.file.readline()
if line:
working = line.rstrip().split(" ")
trad, simp = working[0], working[1]
working = " ".join(working[2:]).split("]")
pinyin = working[0][1:]
english = working[1][1:]
return trad, simp, pinyin, english
else:
raise StopIteration()
你可以分享迭代部分?你使用'.next()'或'.__ next __()'方法還是'__iter__'生成器方法? – 2013-02-10 12:55:00
@MartijnPieters我將分享整個事情 – jsj 2013-02-10 12:59:05