我的问题的灵感来自 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/