繁体   English   中英

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

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

这不是重复的帖子

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

文件名: ABC.dat.gz

内容 = 下载的_blob.read()。 AttributeError: 'bytes' object 没有属性 '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)

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

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

笔记:

不推荐使用 download_as_bytes() 的别名。

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

如果我理解正确,您需要有Bytes对象来创建BytesIO 为此,您不必对downloaded_blob的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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM