How to get file size of objects from google cloud python library?
Asked Answered
S

2

7

Problem

Hello everyone. I am attempting to obtain the file size of an object using the google-cloud python library. This is my current code.

from google.cloud import storage

client = storage.Client()
bucket = client.get_bucket("example-bucket-name")
object = bucket.blob("example-object-name.jpg")

print(object.exists())
>>> True

print(object.chunk_size)
>>> None

It appears to me that the google-cloud library is choosing not to load data into the attributes such as chunk_size, content_type, etc.

Question

How can I make the library explicitly load actual data into the metadata attributes of the blob, instead of defaulting everything to None?

Sudiesudnor answered 8/8, 2019 at 0:43 Comment(2)
this question did not need the python and python-3.x tags since this is not a python issue, per se.Lycaon
@Lycaon agreed, removed the tag.Pleven
D
6

Call get_blob instead of blob.

Review the source code for the function blob_metadata at this link. It shows how to get a variety of metadata attributes of a blob, including its size.

If the above link dies, try looking around in this directory: Storage Client Samples

Darlleen answered 8/8, 2019 at 0:57 Comment(4)
Will get_blob also download the contents of the file? Or will it only retrieve the metadata?Sudiesudnor
To download the object, call download_to_filename(), download_as_string() or similar type of function. These are documented. pypi.org/project/google-cloud-storage and googleapis.github.io/google-cloud-python/latest/storage/…Darlleen
@JohnHanley your link is dead, sadly.Gehlenite
The link is dead.Mckeever
U
6

Call size on Blob.

from google.cloud import storage

# create client
client: storage.client.Client = storage.Client('projectname')

# get bucket
bucket: storage.bucket.Bucket = client.get_bucket('bucketname')

size_in_bytes = bucket.get_blob('filename').size
Unplumbed answered 31/10, 2020 at 10:57 Comment(2)
@SuperEye - The code works. I just verified that on my system. Change the projectname, bucketname, and filename. No issues. What problem did you experience?Darlleen
Yes, this is correct, bucket.get_blob('filename').size works fine.Mckeever

© 2022 - 2024 — McMap. All rights reserved.