微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

AttributeError: 'bytes' 对象在 python 中从 GCS 读取 .gz 文件时没有属性 'read'

如何解决AttributeError: 'bytes' 对象在 python 中从 GCS 读取 .gz 文件时没有属性 'read'

这不是重复的帖子

我在 python 中从 GCS 存储桶读取 .gz(zip) 文件时遇到以下问题

文件名:ABC.dat.gz

content =downloaded_blob.read () 。 AttributeError: 'bytes' 对象没有属性 'read'

代码

    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)

解决方法

我不确定你想在全球范围内实现什么,但我认为至少你可以摆脱这个错误。首先,根据the docs方法download_as_string是:

(已弃用)将此 blob 的内容下载为字节对象。

注意:

弃用了 download_as_bytes() 的别名。

所以你应该改用这个方法。

如果我理解正确,您需要有 Bytes 对象来创建 BytesIO。为此,您不必对 downloaded_blob 变量执行任何操作,因为它已经是正确的类型。所以应该工作的代码如下所示:

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)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。