Very new to Python, and coding in general. I have been working on processing csv files and uploading them to a SFTP server. I wish to check whether the file exists on the server. If it does exist, I want to rename it and archive it to another folder then replace with updated file. If it doesn't exist...I simply want to upload the file.
path2 = '/import/Test/stock_update.csv'
ssh = paramiko.SSHClient()
paramiko.util.log_to_file(log_file)
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
dt = str(datetime.datetime.now())
newname = dt+'stock_update.csv'
archive = 'import/Test/Done/'+newname
ssh.connect('xxxx-mediaserverxxxxxxxxx', port=22, username='xxxxxxxxx', password='xxxxxxxxxx')
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command('ls /tmp')
print "output", ssh_stdout.read() #Reading output of the executed co'mmand
error = ssh_stderr.read()
print "err", error, len(error)
sftp = ssh.open_sftp()
try:
sftp.stat(path2)
except IOError as e:
print e.errno
print errno.ENOENT
if e.errno == errno.ENOENT:
print 'this is if'
sftp.put('C:/Test/fun/stock_update.csv','/import/Test/stock_update.csv',)
else:
print 'this is else'
sftp.rename('/import/Test/stock_update.csv',archive)
sftp.put('C:/Test/fun/stock_update.csv','/import/Test/stock_update.csv',)
finally:
sftp.close()
ssh.close()
I think I am improperly using the else? A file is created on the SFTP server if none exists but nothing is done if the file exists. Individually the lines of code do work.