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

前端 未结 1 354
别跟我提以往
别跟我提以往 2020-12-19 16:21

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 :)

相关标签:
1条回答
  • 2020-12-19 16:44

    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

    0 讨论(0)
提交回复
热议问题