본문 바로가기

개발/Python

GCP 버킷 안의 파일 GCP 주피터 노트북에서 unzip 하기

보통 파이썬으로 통용되는 방법들이 안 되서 좀 헤맸다;;

하지만 웬만하면 로컬 환경에서 unzip 하고 올리십시오... 아래 코드 25G짜리 zip 파일 하나 푸는데 체감상 25분 걸림,,

그리고 반디집 같은 프로그램은 무료인데 GCP 노트북 인스턴스는 시간당 과금..ㅎ

    from google.cloud import storage
    from zipfile import ZipFile
    from zipfile import is_zipfile
    import io

    def zipextract(bucketname, zipfilename_with_path):

        storage_client = storage.Client()
        bucket = storage_client.get_bucket(bucketname)

        destination_blob_pathname = zipfilename_with_path
        
        blob = bucket.blob(destination_blob_pathname)
        zipbytes = io.BytesIO(blob.download_as_string())

        if is_zipfile(zipbytes):
            with ZipFile(zipbytes, 'r') as myzip:
                for contentfilename in myzip.namelist():
                    contentfile = myzip.read(contentfilename)
                    blob = bucket.blob(zipfilename_with_path + "/" + contentfilename)
                    blob.upload_from_string(contentfile)

    zipextract("mybucket", "path/file.zip") # if the file is gs://mybucket/path/file.zip

 

이렇게 하면 zip 파일을 GCP 버킷 내에서 풀 수 있다.