How to Transfer Pandas DataFrame to .csv on SFTP using Paramiko Library in Python?

寵の児 提交于 2020-05-23 07:20:09

问题


I want to transfer a Python dataframe directly as a .csv file to a remote server using Paramiko module. Currently, I save the dataframe as a .csv then I push that .csv file to the server. I stumbled by this similar question How to write pandas dataframe to csv/xls on FTP directly, but is it possible using Paramiko module? Thanks in advance!

This is the simple script I use to transport a .csv file from my directory to the remote server:

import pandas as pd
import paramiko

# Save DataFrame as CSV
file_name = 'file.csv'
df.to_csv(file_name,index=False)

# Connect to Server Via FTP
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(hostname='host',username='user_name',password='password')
ftp_client= ssh_client.open_sftp()

# Upload 'file.csv' to Remote Server
ftp_client.put('path_to_file.csv','path_to_remote_file')

回答1:


Just use SFTPClient.open

with sftp.open('path_to_remote_file', "w") as f:
    f.write(df.to_csv(index=False))


来源:https://stackoverflow.com/questions/55248832/how-to-transfer-pandas-dataframe-to-csv-on-sftp-using-paramiko-library-in-pytho

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!