【问题标题】:Python convert StringIO to binaryPython 将 StringIO 转换为二进制
【发布时间】:2017-07-19 20:54:01
【问题描述】:

我有一个简单的任务:在 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 强制转换为带有str() 的字符串?
  • 好吧,我实际上需要相反的 - pandas 需要 stringIO,我需要将结果转换为 dropbox 的二进制文件

标签: python pandas dropbox stringio


【解决方案1】:

正如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)

【讨论】:

    猜你喜欢
    • 2016-08-13
    • 2020-08-06
    • 2014-11-07
    • 2017-02-04
    • 2021-02-16
    • 1970-01-01
    • 1970-01-01
    • 2016-10-02
    • 2020-10-20
    相关资源
    最近更新 更多