Programming/Python

Python - io.BytesIO 예제

wave35 2024. 10. 19. 16:13

io.BytesIO란

"io.BytesIO"는 바이트 기반의 I/O 작업을 수행할 때 유용합니다.

파일을 다루는 것과 동일한 인터페이스를 제공하지만,

실제 파일 시스템이 아닌 메모리에서 바이트 데이터를 처리합니다.

 

주요기능

메모리에서 바이트 데이터를 처리: 

데이터를 메모리 내에서 처리하므로,  빠르게 바이트 데이터를 임시로 저장하고 조작
파일과 같은 인터페이스: 

파일 객체와 동일한 메서드(예: read(), write(), seek())를 제공, 실제 파일처럼 데이터를 처리

 

 

사용 예시

1. BytesIO 객체에 바이트 데이터 쓰기 및 읽기

import io

# BytesIO 객체 생성
byte_stream = io.BytesIO()

# 바이트 데이터를 메모리 내에 쓰기
byte_stream.write(b'Hello, BytesIO!')

# 스트림의 처음으로 이동
byte_stream.seek(0)

# 메모리 내의 바이트 데이터를 읽기
data = byte_stream.read()
print(data)  # 출력: b'Hello, BytesIO!'

 

 

2. 이미지 처리에서 사용 (with PIL 라이브러리)

이미지를 파일로 저장하지 않고, 메모리 내에서 처리한 후 바로 전송하거나 저장할 때 유용

from PIL import Image
import io

# PIL로 이미지를 생성
image = Image.new('RGB', (100, 100), color='red')

# BytesIO 객체에 이미지를 저장
byte_stream = io.BytesIO()
image.save(byte_stream, format='PNG')

# 스트림의 처음으로 이동
byte_stream.seek(0)

# 메모리에서 이미지 읽기
image_data = byte_stream.read()
# 출력값 : b'\x89PNG\r\n\x1a\n\x00\x00\x...@\xb5\x7

 

3. 네트워크 프로토콜 또는 HTTP 응답에서 사용

excel파일을 메모리에 저장하고 서버 응답으로 바이트 데이터로 처리

import pandas as pd

@router.get("/download/excel")
async def download_excel():
    df_csv = pd.read_csv("https://raw.githubusercontent.com/Datamanim/pandas/main/lol.csv", sep="\t")

    # 메모리에 Excel 파일 생성
    output = io.BytesIO()
    with pd.ExcelWriter(output, engine='xlsxwriter') as writer:
        df_csv.to_excel(writer, index=False)

    # 메모리 포인터를 처음으로 돌리기
    output.seek(0)

    # 메모리에서 StreamingResponse로 반환
    return StreamingResponse(
        output,
        media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        headers={
            "Content-Disposition":"attachment; filename=myFile.xlsx"
        },
    )