본문 바로가기
Google Cloud Platform

파이썬에서 Google GCS에 파일 업로드

by 홍띠 2024. 5. 5.

GCP 환경 설정

권한 - Service Account 생성

  • Service Account 생성 (IAM → Service Account → 서비스 계정 만들기)

  • Key 생성 → JSON → 만들기

GCS 버킷 생성

  • Cloud Storage → 버킷 → 만들기
    이름과 위치 외에는 디폴트 설정 사용

Python 코드 작성

라이브러리 설치

  • GCS 파이썬 클라이언트 설치
pip install google-cloud-storage

생성한 버킷에 파일 업로드

from google.cloud import storage

# 생성한 Key를 사용하도록 storage client 설정
credentials_file = '<위에서 생성한 key를 저장한 위치>'
storage_client = storage.Client.from_service_account_json(credentials_file)

# 버킷 설정
bucket = storage_client.bucket('bucket name')

# 업로드할 원본 파일 위치와 업로드파일명 설정
destination_file_name = "gcs_test/test.json"
source_file_path = "/source/file/path"
blob = bucket.blob(destination_file_name)
blob.upload_from_filename(source_file_path)

print(f"File {source_file_path} uploaded to gs://{bucket_name}/{destination_file_name}")