python connect sftp with key

import pysftp

def upload_file(file_path):

    private_key = "~/.ssh/your-key.pem"  # can use password keyword in Connection instead
    srv = pysftp.Connection(host="your-host", username="user-name", private_key=private_key)
    srv.chdir('/var/web/public_files/media/uploads')  # change directory on remote server
    srv.put(file_path)  # To download a file, replace put with get
    srv.close()  # Close connection

Here is what the above code is Doing:
1. We’re creating a private key variable and setting it to the path of our private key.
2. We’re creating a connection to our server using the pysftp.Connection function.
3. We’re changing the directory on the server to the one where we want to upload our file.
4. We’re uploading the file using the put function.
5. We’re closing the connection.