title: Upload files using SFTP in Python, but create directories if path doesn't exist
body: <p>I want to upload a file on a remote server with Python. I'd like to check beforehand if the remote path is really existing, and if it isn't, to create it. In pseudocode:</p>
  
  <pre><code>if(remote_path not exist):
      create_path(remote_path)
  upload_file(local_file, remote_path)
  </code></pre>
  
  <p>I was thinking about executing a command in Paramiko to create the path (e.g. <code>mkdir -p remote_path</code>). I came up with this:</p>
  
  <pre><code># I didn't test this code
  
  import paramiko, sys
  
  ssh = paramiko.SSHClient()
  ssh.connect(myhost, 22, myusername, mypassword)
  ssh.exec_command('mkdir -p ' + remote_path)
  ssh.close
  
  transport = paramiko.Transport((myhost, 22))
  transport.connect(username = myusername, password = mypassword)
  
  sftp = paramiko.SFTPClient.from_transport(transport)
  sftp.put(local_path, remote_path)
  sftp.close()
  
  transport.close()
  </code></pre>
  
  <p>But this solution doesn't sound good to me, because I close the connection and then reopen it again. Is there a better way to do it?</p>