Python 将 StringIO 转换为二进制
Python convert StringIO to binary
我有一个简单的任务:在 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()
...
如 答案所示,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)
我有一个简单的任务:在 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()
...
如 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)