Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write pandas dataframe to csv/xls on FTP directly

Tags:

python

How to create a .csv or .xls file on ftp directly from Pandas dataframe as I do not want to create one on local machine and then push it on ftp. Many thanks in advance :)

like image 827
trader Avatar asked Sep 06 '17 09:09

trader


1 Answers

As the docs say:

Store a file in binary transfer mode. cmd should be an appropriate STOR command: "STOR filename". file is a file object (opened in binary mode) which is read until EOF using its read() method in blocks of size blocksize to provide the data to be stored…

So, you need to give it a file-like object with an appropriate read method.

A string is not a file-like object, but an io.BytesIO is. So:

from ftplib import *
from StringIO import StringIO
import pandas
import io

ftp = FTP('ftp.mysite.com')
ftp.login('un', 'pw')
ftp.cwd('/')
buffer = StringIO.StringIO()
your_pandas_df.to_csv(buffer)
text = buffer.getvalue()
bio = io.BytesIO(str.encode(text))

ftp.storbinary('STOR filename.csv', bio)

for reference you can refer Python write create file directly in FTP

like image 94
Anurag Misra Avatar answered Nov 14 '22 23:11

Anurag Misra