用pysftp下载文件 [英] Downloading file with pysftp

查看:69
本文介绍了用pysftp下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试加载(直接在本地保存)存储在FTP服务器(SFTP协议)上的.csv文件.我将python与pysftp库结合使用.当我检查文件是否存在时,它返回TRUE.但是,无论我尝试什么,当尝试加载文件时,它似乎都是空的.

I'm trying to load (and directly save locally) a .csv file stored on a FTP Server (SFTP protocol). I'm using Python in combination with pysftp library. When I check if the file exists, it returns TRUE. But when trying to load the file, it seems to be empty, whatever I try.

如何获取(存储)文件到本地环境?我会错过明显的东西吗?

How can I get (and store) the file to my local environment? Do I miss something obvious?

import pysftp

cnopts = pysftp.CnOpts()
cnopts.hostkeys = None

# Make connection to sFTP
with pysftp.Connection(hostname,
                       username=sftp_username,
                       password=sftp_pw,
                       cnopts = cnopts
                       ) as sftp:
    sftp.isfile('directory/file.csv')) ## TRUE
    file = sftp.get('directory/file.csv')
    print(file) ## None

sftp.close()

推荐答案

Connection.get does not return anything. It downloads the remote file to a local path specified by the localpath argument. If you do not specify the argument, it downloads the file to the current working directory.

所以你想要这个:

sftp.get('directory/file.csv', '/local/path/file.csv')


如果您确实想将文件读取为变量(据我了解,您实际上不希望如此),则需要使用


If you really want to read the file to a variable (what I understand that you actually do not want), you need to use Connection.getfo, like:

flo = BytesIO()
sftp.getfo(remotepath, flo)
flo.seek(0)

或者,直接使用Paramiko库(不使用pysftp包装器).
请参见
使用SSH使用Python从服务器读取文件.

Alternatively, use Paramiko library directly (without the pysftp wrapper).
See Read a file from server with SSH using Python.

这篇关于用pysftp下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆