gpt4 book ai didi

Python 将 StringIO 转换为二进制

转载 作者:太空狗 更新时间:2023-10-30 02:54:37 28 4
gpt4 key购买 nike

我有一个简单的任务:在 luigi 中,使用 dropbox-python sdk 将 pandas 数据帧作为 csv 存储在 dropbox 中

通常(例如使用 S3)您可以将 StringIO 用作类似文件的内存中对象。它也适用于 pandas df.to_csv()

不幸的是,dropbox sdk 需要二进制类型,我不知道如何将 StringIO 转换为二进制:

with io.StringIO() as f:
DF.to_csv(f, index=None)
self.client.files_upload(f, path=path, mode=wmode)

TypeError: expected request_binary as binary type, got <class '_io.StringIO'>

ByteIO 不能与 df.to_csv() ...

最佳答案

this 所示答案是,dropbox 需要一个字节对象,而不是一个文件,因此转换为 BytesIO 将无济于事。但是,解决方案比这更简单。您需要做的就是将您的字符串编码为二进制:

csv_str = DF.to_csv(index=None) # get string, rather than StringIO object
self.client.files_upload(csv_str.encode(), path=path, mode=wmode)

关于Python 将 StringIO 转换为二进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45200814/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com