AttributeError: 'bytes' object has no attribute 'read' while reading .gz file from GCS in python

Viewed 1034

This is not a duplicate post

I am facing below issue while reading a .gz(zip) file from GCS bucket in python

file name :ABC.dat.gz

content = downloaded_blob.read () . AttributeError: 'bytes' object has no attribute 'read'

code :

    blob = bucket.blob('sftp/poc/ABC.dat.gz')
    downloaded_blob = blob.download_as_string() 
    print(downloaded_blob)    
    content = downloaded_blob.read () 
    buff = BytesIO (content) # put    content into file object 
    f = gzip.GzipFile(fileobj=buff) 
    print('Lots    of content here 8') 
    res = f.read().decode('utf-8')
    print(res)
1 Answers

I am not sure what do you want to achieve globally, but I think at least you can get rid of this error. First of all, according to the docs method download_as_string is:

(Deprecated) Download the contents of this blob as a bytes object.

Note:

Deprecated alias for download_as_bytes().

So you should use this method instead.

If I understand correctly, you need to have Bytes objects to create BytesIO. For this you do not have to do any action on the downloaded_blob variable as it's already in proper type. So the code that should work looks like here:

blob = bucket.blob('sftp/poc/ABC.dat.gz')
downloaded_blob = blob.download_as_bytes() 
print(downloaded_blob)    
buff = BytesIO (downloaded_blob) # put    content into file object 
f = gzip.GzipFile(fileobj=buff) 
print('Lots    of content here 8') 
res = f.read().decode('utf-8')
print(res)
Related