Python

python- BytesIO와zipFile

finite라이프 2023. 1. 18. 21:30

OpenDart에서 재무제표원본파일을 API를 통해서 Zip FILE(binary)를 받았다.

from zipfile import ZipFile
from io import BytesIO

res = get(url,params={"crtfc_key": api_key, "rcept_no" : rcept_no, "reprt_code":"11014"})

with ZipFile(BytesIO(res.content)) as zipfile:
    zipfile.extractall('설치경로')

with open 은 봐봤어도 with ZipFile 은 처음보고 또 BytesIO()는 또 무엇이란 말인가.

또 다른 포스팅에서 res = requests.get(주소,파라미터등..)로 json을 받을때는 .content를 안써줘도 됐는데 여기선 res.content라고 써줘야한다. requests 공식문서에서 BytesIO와 content내용을 확인했다.

https://requests.readthedocs.io/en/latest/user/quickstart/#binary-response-content

바이너리 데이터로부터 Zip FILE을 만드려면 BytesIO(res.content)가 필요해 보인다.

그냥 res를 넣으면 안되는 걸까? print(res)를 시키면 <Response [200]>이라는 정상적으로 요청이 수행되었다고만 뜬다.

print(res.content)를 실행시키면

이런 형태가 나온다. 이걸 BytesIo()가 Zip FILE로 변환시켜주는 역할을 한다.

with ZipFile( ) as 형태는 파이썬 공식문서에서 확인할 수 있다.

from zipfile import ZipFile
from io import BytesIO

res = get(url,params={"crtfc_key": api_key, "rcept_no" : rcept_no, "reprt_code":"11014"})

with ZipFile(BytesIO(res.content)) as zipfile:
    zipfile.extractall('설치경로')

extractall()을 통해 설치경로에 압축해제를 해준다. 경로로 가보면 저장되어있는 것을 볼 수 있다.