Python 使用 pysftp 下载文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44632588/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 00:16:26  来源:igfitidea点击:

Downloading file with pysftp

pythonsftppysftp

提问by Dendrobates

I'm trying to load (and directly save locally) a .csvfile 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.

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

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

回答by Martin Prikryl

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

Connection.get不返回任何东西。它将远程文件下载到localpath参数指定的本地路径。如果不指定参数,它会将文件下载到当前工作目录。

So you want this:

所以你想要这个:

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:

如果你真的想把文件读到一个变量中(我知道你实际上不想要),你需要使用Connection.getfo,比如:

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

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

或者,直接使用 Paramiko 库(没有 pysftp 包装器)。
参阅使用 Python 使用 SSH 从服务器读取文件