问题描述
这不是重复的帖子
我在 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)