[英]Where to close the file handler for read and write mode?
例如,我想搜索一些单词的内容并将它们缓存到文件中。 该程序可能会运行多次,因此每次都会将新条目写入文件。 对于现有单词,只需返回其内容而无需重做工作。 对于下面的代码,关闭文件处理程序的位置在哪里? 或者这是完成这项工作的正确方法吗?
class Crawler(object):
def __int__(self):
self.file_handler = open('word.txt', 'a+')
self.cache = self.load_words()
def load_words(self):
cache = {}
for line in self.file_handler:
columns = line.strip('\t')
cache[columns[0]] = columns[1]
return cache
def search(self, word):
# 1. return word's content immediately
if word in self.cache:
return self.cache[word]
# 2. Otherwise, fetch the word's content
content = get_content(word)
# 3. Append the new word-content pair into the cache file
self.file_handler.write(word + '\t' + content)
self.cache[word] = content
return content
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.