Python将StringIO转换为二进制

4

我有一个简单的任务:在luigi中,使用dropbox-python sdk将pandas dataframe存储为csv文件。

通常情况下(例如使用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()一起使用...


尝试使用str()BytesIO强制转换为字符串吗? - Brian Cain
1
我实际上需要相反的 - pandas需要stringIO,而我需要将结果转换为二进制以供“dropbox”使用。 - Philipp_Kats
1个回答

6
此答案所示,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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接