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()
答案 0 :(得分:10)
Connection.get
不返回任何内容。它将远程文件下载到localpath
参数指定的本地路径。如果未指定参数,则会将文件下载到当前工作目录。
所以你想要这个:
sftp.get('directory/file.csv', '/local/path/file.csv')
如果您真的想要将文件读取到变量(我理解您实际上不需要),则需要使用Connection.getfo
,例如:
flo = BytesIO()
sftp.getfo(remotepath, flo)
或者,直接使用Paramiko库(不使用pysftp包装器) 请参阅Read a file from server with SSH using Python。