gpt4 book ai didi

Python 自定义迭代器 : Close a file on StopIteration

转载 作者:太空狗 更新时间:2023-10-29 20:50:15 27 4
gpt4 key购买 nike

我编写了一个迭代器类,它在 __init__ 中打开一个文件。

def __init__(self, path):
self.file = open(path, "r")

如何在迭代完成后自动关闭该文件?

完成类(class):

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()

最佳答案

编写整个内容的更好方法是将开头和迭代保留在一个地方:

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.path = path

def __is_comment(self, line):
return line.startswith("#")

def __iter__(self):
with open(self.path) as f:
for line in f:
if self.__is_comment(line):
continue

working = line.rstrip().split(" ")
trad, simp = working[0], working[1]
working = " ".join(working[2:]).split("]")
pinyin = working[0][1:]
english = working[1][1:]
yield trad, simp, pinyin, english

这将等到您真正需要它时才打开文件,并在完成后自动关闭它。它的代码也更少。

如果你真的想进入“发电机真棒!”心态:

def skip_comments(f):
for line in f:
if not.startswith('#'):
yield line

...

def __iter__(self):
with open(self.path) as f:
for line in skip_comments(f):
working = ....

关于Python 自定义迭代器 : Close a file on StopIteration,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14797930/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com