MST
星途 面试题库

面试题:Python上下文管理器原理及复杂文件操作应用

假设你需要对一个大文件进行处理,这个文件每行是JSON格式数据。要求在处理过程中如果遇到解析JSON失败的行,记录下错误行号并继续处理。请使用上下文管理器来实现这个功能,并且说明上下文管理器的`__enter__`和`__exit__`方法在这个场景中的作用。
43.0万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
import json


class JsonFileProcessor:
    def __init__(self, file_path):
        self.file_path = file_path
        self.error_lines = []

    def __enter__(self):
        self.file = open(self.file_path, 'r', encoding='utf-8')
        return self

    def process_file(self):
        for line_number, line in enumerate(self.file, start=1):
            try:
                json.loads(line)
            except json.JSONDecodeError:
                self.error_lines.append(line_number)

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.file.close()
        if self.error_lines:
            print(f"解析失败的行号: {self.error_lines}")


使用示例:

with JsonFileProcessor('big_file.json') as processor:
    processor.process_file()

在这个场景中:

  • __enter__方法的作用:打开要处理的文件,并返回上下文管理器实例自身。这样在with语句块中就可以使用这个实例来进行文件处理操作。
  • __exit__方法的作用:关闭已经打开的文件,并在文件处理完毕后,检查是否有解析失败的行号记录在error_lines列表中,如果有则打印出这些错误行号。