面试题答案
一键面试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
列表中,如果有则打印出这些错误行号。