$ pip install --upgrade google-cloud-storage
from google.cloud import storage
client = storage.Client()
bucket = storage.Bucket(client)
bucket.name = "test-bucket"
bucket.location = "asia-northeast1"
client.create_bucket(bucket)
bucket_name = "test-bucket"
bucket = client.get_bucket(bucket_name)
for bucket in client.list_buckets():
print(bucket.name)
# test-bucket1
# test-bucket2
# test-bucket3
print(bucket.exists())
# True
bucket.delete(force=True)
If you want to send a delete request to a bucket, the bucket must be empty. By setting the parameter "force" to True, you can delete all the objects in the bucket and then delete the bucket. (Empty with True, default False) However, be aware that if there are more than 256 objects in the bucket, a ValueError will occur.
for blob in client.list_blobs(bucket_name):
print(blob.name)
# test_dir/
# test_dir/hoge.txt
# test_dir/test_file_in_dir_1.txt
# test_dir/test_file_in_dir_2.txt
# test_file_1.txt
# test_file_2.txt
for blob in client.list_blobs(bucket_name, prefix="test_dir/test"):
print(blob.name)
# test_dir/test_file_in_dir_1.txt
# test_dir/test_file_in_dir_2.txt
blob = bucket.blob("test_dir/test_file_in_dir_1.txt") #Specify storage path
print(blob.exists())
# True
blob.download_to_filename("test_file_in_dir_1.txt") #Specify the download destination path
blob.upload_from_filename("test_file_in_dir_1.txt") #Specify the upload source path
blob.delete()
google-cloud-storage Library Reference https://googleapis.dev/python/storage/latest/client.html
Recommended Posts