문제상황:
파이썬으로 작성된 로그 처리 스크립트에서 에러가 발생했습니다. 이 코드는 주어진 로그 파일에서 특정 패턴을 찾아서 새로운 파일에 기록하는 작업을 수행합니다.
import re
def process_log_file(input_file, output_file, pattern):
with open(input_file, 'r') as f_in:
with open(output_file, 'w') as f_out:
for line in f_in:
if re.search(pattern, line):
f_out.write(line)
f_out.write("Processing completed.")
input_file = "example.log"
output_file = "output.log"
pattern = r"ERROR"
process_log_file(input_file, output_file, pattern)
에러로그 내용:
ValueError: I/O operation on closed file
해결방법:
에러가 수정된 코드와 수정된 부분에 대한 주석:
import re
def process_log_file(input_file, output_file, pattern):
with open(input_file, 'r') as f_in:
with open(output_file, 'w') as f_out:
for line in f_in:
if re.search(pattern, line):
f_out.write(line)
f_out.write("Processing completed.") # 수정된 부분
input_file = "example.log"
output_file = "output.log"
pattern = r"ERROR"
process_log_file(input_file, output_file, pattern)
원인분석:
위 코드에서 발생한 에러는 with 문을 벗어난 후에 파일 객체 f_out에 I/O 작업을 수행하려고 했기 때문입니다. with 문을 사용하여 파일 객체를 열게 되면, 해당 블록이 종료되는 시점에서 자동으로 파일이 닫힙니다. 따라서 파일이 닫힌 상태에서 작업을 시도하면 ValueError가 발생합니다.
해결방법은 해당 I/O 작업을 with 블록 내부로 이동시켜 파일이 닫히기 전에 작업을 완료하도록 수정하는 것입니다.
참고링크:
728x90