Upload file via sftp with python

I found the answer to my own question.

import pysftp

srv = pysftp.Connection(host="www.destination.com", username="root",
password="password",log="./temp/pysftp.log")

with srv.cd('public'): #chdir to public
    srv.put('C:\Users\XXX\Dropbox\test.txt') #upload file to nodejs/

# Closes the connection
srv.close()

Put the srv.put inside with srv.cd


import pysftp

with pysftp.Connection(host="www.destination.com", username="root",
password="password",log="./temp/pysftp.log") as sftp:

  sftp.cwd('/root/public')  # The full path
  sftp.put('C:\Users\XXX\Dropbox\test.txt')  # Upload the file

No sftp.close() is needed, because the connection is closed automatically at the end of the with-block

I did a minor change with cd to cwd

Syntax -

# sftp.put('/my/local/filename')  # upload file to public/ on remote
# sftp.get('remote_file')         # get a remote file