Search code examples
pythongoogle-cloud-platformgoogle-cloud-storagegoogle-cloud-python

How to get the blob size of Cloud Storage object?


I could get the size from gsutil.

✗ gsutil du gs://<bucket>/test/1561402306
100          gs://<bucket>/test/1561402306

I could confirm the length and content via download_as_string. However, the size property always returns None from SDK/API.

How could I get the size of Cloud Storage object without downloaded?

from google.cloud import storage

client = storage.Client()
bucket = client.get_bucket(bucket_name)
blob = bucket.blob(blob_name)
print(len(blob.download_as_string().decode()))
print(blob.size)

Output:

100
None

Solution

  • You have to use get_blob() to get the blob blob = bucket.get_blob(blob_name) instead of bucket.blob(), which is a factory constructor for blob object.

    Look to the difference between the two functions at get_blob() and blob().