python sftp to determine if a file exists

SFTP supports the usual FTP commands (chdir, mkdir , etc.), so use these commands:

sftp = paramiko.SFTPClient.from_transport(transport)

try:

sftp.chdir(remote_path) # Test if remote_path exists

except IOError:

sftp.mkdir(remote_path) # Create remote_path

sftp.chdir (remote_path)

sftp.put(local_path, '.') # At this point, you are in remote_path in either case

sftp.close()

To fully emulate mkdir -p , you can use remote_path recursively:

import os.path

def mkdir_p(sftp, remote_directory):

"""Change to this directory, recursively making new folders if needed.

Returns True if any folders were created."""

if remote_directory == '/':

# absolute path so change directory to root

sftp.chdir ('/')

return

if remote_directory == '':

# top-level relative directory must exist

return

try:

sftp.chdir(remote_directory) # sub-directory exists

except IOError:

dirname, basename = os.path.split(remote_directory.rstrip('/'))

mkdir_p(sftp, dirname) # make parent directories

sftp.mkdir(basename) # sub-directory missing, so created it

sftp.chdir (basename)

return True

sftp = paramiko.SFTPClient.from_transport(transport)

mkdir_p(sftp, remote_path)

sftp.put(local_path, '.') # At this point, you are in remote_path

sftp.close()

Of course, if remote_path also contains a remote filename, then it needs to be split, and that directory is passed to mkdir_p, using the filename instead of '.'. in sftp.put.

Related: python sftp to determine if a file exists