PYTHON · 파일/IO
대용량 파일 처리
메모리를 효율적으로 사용하며 대용량 파일을 읽고 처리하는 기법입니다.
파일/IO중급대용량파일chunkStringIO
핵심 설명
메모리를 효율적으로 사용하며 대용량 파일을 읽고 처리하는 기법입니다.
Python code
from pathlib import Path
import io
# 줄 단위 읽기 (메모리 효율적)
def count_lines(filepath: str) -> int:
count = 0
with open(filepath, "r", encoding="utf-8") as f:
for _ in f: # 한 줄씩 읽음
count += 1
return count
# 청크 단위 읽기 (바이너리)
def process_large_file(filepath: str, chunk_size: int = 8192):
total_bytes = 0
with open(filepath, "rb") as f:
while chunk := f.read(chunk_size):
total_bytes += len(chunk)
return total_bytes
# 제너레이터로 CSV 처리
def read_csv_lazy(filepath: str):
with open(filepath, "r", encoding="utf-8") as f:
header = next(f).strip().split(",")
for line in f:
values = line.strip().split(",")
yield dict(zip(header, values))
# 메모리 효율적 변환
def transform_file(src: str, dst: str):
with open(src, "r") as fin, open(dst, "w") as fout:
for line in fin:
fout.write(line.upper())
# StringIO: 메모리 내 파일 객체
buffer = io.StringIO()
buffer.write("Hello\nWorld\n")
buffer.seek(0)
for line in buffer:
print(f" 메모리 파일: {line.strip()}")
print("대용량 파일 처리 패턴 준비 완료")학습 팁
for line in file:은 한 줄씩 읽어 메모리 사용이 일정합니다. GB 단위 파일도 처리 가능합니다.
주의할 점
file.read()는 파일 전체를 메모리에 올립니다. 대용량 파일에서는 줄 단위나 청크 단위로 읽으세요.
자주 묻는 질문
대용량 파일 처리란 무엇인가요?
메모리를 효율적으로 사용하며 대용량 파일을 읽고 처리하는 기법입니다.
대용량 파일 처리 학습 시 주의할 점은 무엇인가요?
file.read() 는 파일 전체를 메모리에 올립니다. 대용량 파일에서는 줄 단위나 청크 단위로 읽으세요.
Continue Learning
Python 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.