Python 中来自 AWS S3 的 gzip 文件的内容仅返回空字节
Contents of a gzip file from a AWS S3 in Python only returning null bytes
AWS Comprehend 在 S3 存储桶中创建了一个名为 output.tar.gz
的文件。
我正在尝试使用 Python 将此文件加载到内存中并尝试了以下操作:
import boto3
from io import BytesIO
import gzip
s3 = boto3.client("s3")
obj = s3.get_object(Bucket=BUCKET, Key=KEY)
mycontentzip = gzip.GzipFile(fileobj=BytesIO(obj['Body'].read())).read()
lines = mycontentzip.decode("utf-8")
我也尝试过关于这个 post 的解决方案,包括不再需要 BytesIO:
Reading contents of a gzip file from a AWS S3 in Python
我可以将这些解决方案用于 return 不是 .gz
的测试文件,以确保我可以正确连接到 S3 存储桶。
在所有尝试中,returned 是一个只有以下内容的文件:
00\x00\x00\x00\x00\x00\x00\x00\x00
\x00\x00\x\x00\x00\x00\x00\x00\x00
\x00\x00\x00\x00\x00\x...
我正在使用
Python=3.7.7
Boto3=1.10.5
我也尝试过从 AWS 控制台手动下载文件。奇怪的是,该文件在 MacOS 10.15.6 中解压缩为“.jsonl”文件。但是,在 VScode 中作为 JSON.
可以正常打开
有其他人遇到过这个问题吗?
提前感谢您的任何想法。
#---------------------------------------- --
更新
谢谢@AKX。它是 Tarfile。在文档中发现 Tarfile 模块中有一个 Gzip 读取模式:https://docs.python.org/3/library/tarfile.html
s3 = boto3.resource("s3")
obj = s3.Object(BUCKET, KEY)
tar = tarfile.open(fileobj=BytesIO(obj.get()["Body"].read()), mode='r|gz')
tar.extractall('tmp_folder')
尝试将存档中的单个文件读入内存,但将其保存到磁盘并再次读取更容易。我正在处理少量数据。
这是一个 tar.gz 文件,即使用 gzip
算法压缩的 tar
档案。
如果您只是用 gzip.GzipFile()
阅读它,您仍然有一个二进制 tar 存档需要解释。
使用tarfile
模块读取; tar 存档,如 zip,可以包含多个文件,其中之一是您最终看到的 .jsonl
文件。
AWS Comprehend 在 S3 存储桶中创建了一个名为 output.tar.gz
的文件。
我正在尝试使用 Python 将此文件加载到内存中并尝试了以下操作:
import boto3
from io import BytesIO
import gzip
s3 = boto3.client("s3")
obj = s3.get_object(Bucket=BUCKET, Key=KEY)
mycontentzip = gzip.GzipFile(fileobj=BytesIO(obj['Body'].read())).read()
lines = mycontentzip.decode("utf-8")
我也尝试过关于这个 post 的解决方案,包括不再需要 BytesIO: Reading contents of a gzip file from a AWS S3 in Python
我可以将这些解决方案用于 return 不是 .gz
的测试文件,以确保我可以正确连接到 S3 存储桶。
在所有尝试中,returned 是一个只有以下内容的文件:
00\x00\x00\x00\x00\x00\x00\x00\x00
\x00\x00\x\x00\x00\x00\x00\x00\x00
\x00\x00\x00\x00\x00\x...
我正在使用 Python=3.7.7 Boto3=1.10.5
我也尝试过从 AWS 控制台手动下载文件。奇怪的是,该文件在 MacOS 10.15.6 中解压缩为“.jsonl”文件。但是,在 VScode 中作为 JSON.
可以正常打开有其他人遇到过这个问题吗?
提前感谢您的任何想法。
#---------------------------------------- --
更新
谢谢@AKX。它是 Tarfile。在文档中发现 Tarfile 模块中有一个 Gzip 读取模式:https://docs.python.org/3/library/tarfile.html
s3 = boto3.resource("s3")
obj = s3.Object(BUCKET, KEY)
tar = tarfile.open(fileobj=BytesIO(obj.get()["Body"].read()), mode='r|gz')
tar.extractall('tmp_folder')
尝试将存档中的单个文件读入内存,但将其保存到磁盘并再次读取更容易。我正在处理少量数据。
这是一个 tar.gz 文件,即使用 gzip
算法压缩的 tar
档案。
如果您只是用 gzip.GzipFile()
阅读它,您仍然有一个二进制 tar 存档需要解释。
使用tarfile
模块读取; tar 存档,如 zip,可以包含多个文件,其中之一是您最终看到的 .jsonl
文件。