【问题标题】:AttributeError: 'bytes' object has no attribute 'read' while reading .gz file from GCS in pythonAttributeError:'bytes'对象在python中从GCS读取.gz文件时没有属性'read'
【发布时间】:2021-06-03 23:19:22
【问题描述】:

这不是重复的帖子

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

文件名:ABC.dat.gz

内容 = 下载的_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)

【问题讨论】:

  • 您将 blob 作为字节对象下载。 byte 类型没有任何称为 read 的方法,这就是您收到错误的原因。你想读什么?您已经将 blob 读入字节对象
  • 感谢克里斯。实际上我正在尝试从 GCS 读取 .gz 文件并打印其中的内容
  • 但是你这里没有文件对象,你有一个字节对象。也许您想先下载 zip 文件然后解压缩。 googleapis.dev/python/storage/latest/…
  • 谢谢Chirs,我正在尝试下载文件但它没有发生,你能帮我修改上面的代码吗

标签: python python-3.x google-cloud-platform google-cloud-storage


【解决方案1】:

我不确定你想在全球范围内实现什么,但我认为至少你可以摆脱这个错误。首先,根据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)

【讨论】:

  • 嗨@Wytrzymały Wiktor,@vitooh,我尝试将此逻辑放在云函数中并执行它。它给了我以下错误。 .大多数时候我都收到这个错误。 AttributeError: 'str' 对象没有属性 'blob'"
  • 如果此错误是指提供的代码,则问题必须与 bucket 的初始化有关。这在此代码示例之外。由于这是不同的问题,我建议创建新问题添加这部分代码。
  • @vitooh 感谢您的回复。现在我可以读取数据了。你能告诉我如何将打印的数据上传到存储桶
  • 只是问新问题,我总是没有时间,但是有很多人可以提供帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多