天天看點

python字元串轉二進制代碼_Python将StringIO轉換為二進制

我有一個簡單的任務:在luigi中,使用dropbox-python sdk将pandas資料幀存儲為dropbox中的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

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,dropbox,pandas,stringio

來源: https://codeday.me/bug/20190622/1264559.html