Search code examples
pythonsftppysftp

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


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:\Users\Me\Documents\test 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!


Solution

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

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

    Some notes: