【问题标题】:Unable to append data to an existing csv file in AWS S3 using python无法使用 python 将数据附加到 AWS S3 中的现有 csv 文件
【发布时间】:2021-09-20 14:27:10
【问题描述】:

我的 s3 存储桶中有一个 csv 文件,并在我的本地计算机中配置了 aws cli。每当我调用我的 python 脚本时,我都想将数据附加到该 csv 文件中,但我无法做到这一点。

s3_client = boto3.client('s3')
df = pd.DataFrame(data_list)
bytes_to_write = df.to_csv(None, header=None, index=False).encode()
file_name = 'test.csv'
# get the existing file
current_data = s3_client.get_object(Bucket='test-bucket', Key=file_name)
# append
appended_data = current_data + bytes_to_write
# overwrite
s3_client.put_object(Body=appended_data, Bucket='test-bucket', Key=file_name)
enter code here

我已经尝试了上面的代码,但不幸的是无法完成操作,我得到了以下错误

Traceback (most recent call last):
  File "script.py", line 17, in <module>
    appended_data = current_data + bytes_to_write
TypeError: unsupported operand type(s) for +: 'dict' and 'bytes'

有什么解决办法吗?请帮帮我!

【问题讨论】:

  • 我可以从这个错误日志中了解到,你的 current_data 和 bytes_to_write 的格式不一样。您需要将 current_data 转换为数据帧,然后尝试上传。
  • 如何转换成数据框,我试过这个"df2 =pd.DataFrame(current_data)" 但还是有同样的错误

标签: python pandas amazon-web-services amazon-s3 boto3


【解决方案1】:
current_data = s3_client.get_object(Bucket='test-bucket', Key=file_name)

here 所述,get_object 返回一个字典

你可能正在寻找

s3_client.get_object(Bucket='test-bucket', Key=file_name)['Body'].read().decode("utf-8")

【讨论】:

  • 您好,感谢您的回复我已更改行“current_data = s3_client.get_object(Bucket='test-lambda-shyam', Key=file_name)['Body'].read() .decode("utf-8")"。但我收到了这样的错误“回溯(最近一次调用最后一次):文件“script.py”,第 19 行,在 appended_data = current_data + bytes_to_write TypeError:只能将 str(而不是“bytes”)连接到 str”
  • .decode("utf-8") 正在将字节转换为 str - 只需将其删除
猜你喜欢
  • 2020-12-26
  • 2021-09-21
  • 2019-03-02
  • 2020-12-14
  • 1970-01-01
  • 2021-09-04
  • 2018-10-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多