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()
To download a remote file from the server using pysftp, we have to open a connection and from the sftp instance and use the get method that expects the path of a remote file that will be downloaded, and the second argument as a local path where the file should be stored.
In the below example we login to a remote server using sftp and then get and put some file in that directory. When we run the above code we are able to see the list of files present in the allcode directory and also put and get some file in that directory.
SFTP, abbreviated for SSH File Transfer Protocol and known as Secure File Transfer Protocol, is a network protocol that allows us to access files, transfer them and manage them over any dependable data stream.
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.
So if you want to download to a specific local directory instead, 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:
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.
Obligatory warning: Do not set cnopts.hostkeys = None
, unless you do not care about security. For the correct solution see Verify host key with pysftp.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With