0

I am trying to read file from Google cloud storage bucket with blob.open but it is giving error that blob does not have open attribute! How to resolve this ? Thank you in advance!

# Instantiates a client
#storage_client = storage.Client()
storage_client = storage.Client.from_service_account_json('service-account-file.json')
# The name of bucket
bucket_name = "bucket"
file_name = "sample.txt"

bucket = storage_client.bucket(bucket_name)
blob = bucket.blob(file_name)
blob = bucket.blob(file_name)
with blob.open("rt") as f:
   print(f.read())```

Traceback (most recent call last):File "test/read-test-3.py", line 15, in <module> with blobs.open("rt") as f: AttributeError: 'Blob' object has no attribute 'open'
Sammlona
  • 23
  • 6

2 Answers2

2

The Google Cloud Storage Python SDK does not provide an open() or a close() method.

The correcct workflow is to declare the object and then read it. The equivalent code is:

bucket = storage_client.bucket(bucket_name)
blob = bucket.blob(file_name)
data = blob.download_as_string()
print(data)
John Hanley
  • 74,467
  • 6
  • 95
  • 159
1

you can find what you are looking for on this doc:

https://cloud.google.com/python/docs/reference/storage/latest/blobs#example-5

from google.cloud import storage
client = storage.Client()
bucket = client.bucket("bucket-name")
blob = bucket.blob("blob-name.txt")
with blob.open("rt") as f:
    print(f.read())

This return a string object.