繁体   English   中英

在哪里关闭读写模式的文件处理程序?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM