Download files from SFTP server to specific local directory using Python pysftp

Question:

I’m attempting to download a set of files from an SFTP server. I can download the files successfully, but now I want to change the script so that as the files download, they go to a specified directory on my local server.

I attempted doing this with the sftp.getfo() command, but am getting an error:

getfo() got an unexpected keyword argument ‘fl’

#SET LOCAL DIRECTORY
directory1 = r'C:UsersMeDocumentstest sftp'

#CONNECT TO SFTP
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
sftp = pysftp.Connection(host = hostname, username = usereu, password = passeu, cnopts = cnopts)
print("Connection successfully established ... ")

#DOWNLOAD ALL FILES IN FOLDER
files = sftp.listdir()
for file in files:
   sftp.getfo(remotepath = file, fl = directory1)
   print(file,' downloaded successfully ')

Am I using the right command here or is there a better way to do this?

Thanks!

Asked By: Tyler Moore

||

Answers:

To download a file to local path, use Connection.get (not getfo):

sftp.get(remotepath=file, localpath=os.path.join(directory1, file))

Some notes:

Answered By: Martin Prikryl
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.