Code ReviewElementary~15 min
Review: Resource Leak Prevention
pythonresource-managementfile-handlingdatabase
Code Review Task
Please review the following Python code.
Background
This code processes log files and saves them to a database. It is expected to process a large number of log files.
Review Aspects
- Appropriateness of resource management
- File handle handling
- Database connection management
- Cleanup in case of exceptions
Your Answer
log_processor.pypython
import sqlite3 def process_log_file(filename, db_path): """Process log file and save to database""" conn = sqlite3.connect(db_path) cursor = conn.cursor() f = open(filename, 'r') lines = f.readlines() if not lines: return 0 for line in lines: if line.strip(): cursor.execute(f"INSERT INTO logs (message) VALUES ('{line.strip()}')") conn.commit() return len(lines)行番号をクリックしてコメントを追加(Shift+クリックで範囲選択)
Minimum 100 characters required
Add comments and enter at least 100 characters in the summary
Model Answer
Submit your answer or click "Show" to view the model answer.