💡

【Google Cloud Storage】バケットの所定フォルダ内のファイル一覧を出力しCSVファイルに保管

2023/02/17に公開

概要

標記の通り、GCSにて"bucket_A"を作成、その直下に作成した"folder_A"に保存したファイル一覧を出力して、CSVに保管する方法を解説する。保管するCSVファイルは、今回実行するファイルと同じ階層に保存しているfile_names.csvである。全体のコードは末尾に記載しているので、お急ぎの方はそちらを参照いただきたい。

必要なライブラリをインポート

まずは、必要なライブラリを一通りインポートする。

import datetime
import csv
from dateutil.relativedelta import relativedelta
from google.oauth2 import service_account
import os
import json
from google.cloud import storage

アカウント情報を取得

次に、個人のGCSにアクセスするために必要なtest-gcs.jsonを取得する。このファイルは、本プログラムと同じ階層に保存されている。ファイルには、type / project_id / private_key_id / private_key / client_emailなどが保存されている。

key_path = os.path.join(os.path.dirname(
    os.path.abspath(__file__)), 'test-gcs.json')
service_account_info = json.load(open(key_path))
credentials = service_account.Credentials.from_service_account_info(
    service_account_info)
storage_client = storage.Client(
    credentials=credentials,
    project=credentials.project_id,
)

バケット名、フォルダ名を指定

次に、バケット名とフォルダ名を指定する。一番最後のfile_names = [file.name for file in files]では、CSVファイルに書き込むファイル名のリストを作成している。

bucket_name = 'bucket_A'
bucket = storage_client.bucket(bucket_name)
folder_name = "folder_A"
prefix = folder_name + '/'
files = bucket.list_blobs(prefix=prefix)

file_names = [file.name for file in files]

CSVファイルを作成

最後に、CSVファイルにファイル名のリストを書き込む。file_names.csvを指定しファイルを開く。そこに対して、for file_name in file_namesと、上記で作成したfile_namesというリストにloopをかける形で、ファイル名を書き込んでいく。

with open('file_names.csv', mode='w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(['File Name'])
    for file_name in file_names:
        writer.writerow([file_name])

全体のコード

import datetime
import csv
from dateutil.relativedelta import relativedelta
from google.oauth2 import service_account
import os
import json
from google.cloud import storage

key_path = os.path.join(os.path.dirname(
    os.path.abspath(__file__)), 'test-gcs.json')
service_account_info = json.load(open(key_path))
credentials = service_account.Credentials.from_service_account_info(
    service_account_info)
storage_client = storage.Client(
    credentials=credentials,
    project=credentials.project_id,
)
bucket_name = 'bucket_A'
bucket = storage_client.bucket(bucket_name)
folder_name = "folder_A"
prefix = folder_name + '/'
files = bucket.list_blobs(prefix=prefix)

file_names = [file.name for file in files]
with open('file_names.csv', mode='w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(['File Name'])
    for file_name in file_names:
        writer.writerow([file_name])

Discussion