python - s3.upload_fileobj 给出错误需要类似字节的对象

标签 python pandas amazon-s3

我的问题的灵感来自 previous SO关于此主题:在 Amazon Web Services (AWS) S3 中上传 DataFrame 并将其保存为 csv 文件。使用 Python3,我想使用 s3.upload_fileobj – 分段上传 – 使数据传输到 S3 更快。当我在接受的答案中运行代码时,我收到一条错误消息:“TypeError:需要类似字节的对象,而不是“str””。

该答案最近已被多次投票。所以我想一定有一种方法可以在Python3中运行这段代码而不出错。

请找到下面的代码。为了方便起见,我们使用一个简单的 DataFrame。实际上,这个 DataFrame 要大得多(大约 500 MB)。

import pandas as pd
import io

df = pd.DataFrame({'A':[1,2,3], 'B':[6,7,8]})

代码如下。为了方便起见,我将其转入函数中:

def upload_file(dataframe, bucket, key):
    """dat=DataFrame, bucket=bucket name in AWS S3, key=key name in AWS S3"""
    s3 = boto3.client('s3')
    csv_buffer = io.BytesIO()
    dataframe.to_csv(csv_buffer, compression='gzip')
    s3.upload_fileobj(csv_buffer, bucket, key)

upload_file(df, your-bucket, your-key)

非常感谢您的建议!

最佳答案

出发this reference ,看来您需要在 BytesIO 周围包装一个 gzip.GzipFile 对象,然后该对象将为您执行压缩。

import io
import gzip

buffer = io.BytesIO()     
with gzip.GzipFile(fileobj=buffer, mode="wb") as f:
    f.write(df.to_csv().encode())
buffer.seek(0)

s3.upload_fileobj(buffer, bucket, key)
<小时/>

最小可验证示例

import io
import gzip
import zlib

# Encode
df = pd.DataFrame({'A':[1,2,3], 'B':[6,7,8]})

buffer = io.BytesIO()     
with gzip.GzipFile(fileobj=buffer, mode="wb") as f:
    f.write(df.to_csv().encode())

buffer.getvalue()
# b'\x1f\x8b\x08\x00\xf0\x0b\x11]\x02\xff\xd3q\xd4q\xe22\xd01\xd41\xe32\xd41\xd21\xe72\xd21\xd6\xb1\xe0\x02\x00Td\xc2\xf5\x17\x00\x00\x00'

# Decode
print(zlib.decompress(out.getvalue(), 16+zlib.MAX_WBITS).decode())

# ,A,B
# 0,1,6
# 1,2,7
# 2,3,8

关于python - s3.upload_fileobj 给出错误需要类似字节的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56662609/

相关文章:

python - 将(出发地、目的地、距离)转换为距离矩阵

python - 基于对合并数据帧

.net - 如何使用适用于 .NET 的 AWS 开发工具包将多个文件异步上传到 Amazon S3?

python - 在 Flask 中测试文件上传

python - 为什么 doctest 没有检测到我的测试?

python - 使用 pandas 分析超过 20G 的数据帧,内存不足,指定 chunksize 时仍然无法正常工作

amazon-s3 - 从 S3 cloudfront 静态网站重定向中删除 root/

django - 不可压缩文件错误: 'scripts/app.js' isn't accessible via COMPRESS_URL ('http://my-bucket.s3-us-west-2.amazonaws.com/' ) and can't be compressed

python - 如何抑制 "Future warning" tensorflow ?

python - 如何使用 python 将国家名称转换为 ISO 3166-1 alpha-2 值