오늘의 인기 글
최근 글
최근 댓글
Today
Total
04-28 00:01
관리 메뉴

우노

[GCP] GCS → Bigquery with Python 본문

GCP/Bigquery

[GCP] GCS → Bigquery with Python

운호(Noah) 2024. 3. 21. 14:55

들어가기 앞서,

  • 해당 포스팅에선 Google Cloud Storage(GCS)에서 CSV 파일을 읽어서 Google BigQuery에 데이터를 저장하는 코드에 대해서 다뤄보겠습니다.

예제 코드

# 필요한 라이브러리를 불러옵니다.
from google.cloud import storage, bigquery
import pandas as pd
from io import StringIO

# Google Cloud Storage(GCS) 설정
bucket_name = 'your_bucket_name'  # GCS 버킷 이름
prefix = 'your_file_prefix'  # 파일 경로 및 이름의 공통된 시작 부분
gcs_client = storage.Client()  # GCS 클라이언트 객체 생성
bucket = gcs_client.bucket(bucket_name)  # 버킷 객체 생성

# BigQuery 설정
bq_client = bigquery.Client()  # BigQuery 클라이언트 객체 생성
dataset_id = 'your_dataset_id'  # 데이터셋 ID
table_id = 'your_table_id'  # 테이블 ID
table_ref = bq_client.dataset(dataset_id).table(table_id)  # 테이블 참조 생성

# GCS에서 CSV 파일들을 읽고 BigQuery에 저장하는 과정
blobs = bucket.list_blobs(prefix=prefix)  # 지정된 경로의 파일 목록을 가져옵니다.
for blob in blobs:

    # CSV 파일 읽기
    data = blob.download_as_string()  # 파일 내용을 문자열로 다운로드
    df = pd.read_csv(StringIO(data.decode('utf-8')))  # 데이터프레임으로 변환

    # BigQuery에 데이터프레임 저장
    job = bq_client.load_table_from_dataframe(df, table_ref)
    job.result()  # Job이 완료될 때까지 대기

    print(f'{blob.name} 처리 완료')

'GCP > Bigquery' 카테고리의 다른 글

[GCP] Bigquery 테이블 생성 with Python  (0) 2024.03.21
Comments