0

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.

dbell
  • 50
  • 10
  • Have working now. Above code has been edited to reflect changes. Need to add in checks for the input file. – dbell Apr 28 '14 at 16:23
  • don't forget to change your password after you post it on stackoverflow. – Chris Wesseling Apr 28 '14 at 16:48
  • Your use of `else` is [ok](http://stackoverflow.com/a/855764/383793). except you might want to `raise` if `e.errno != errno.ENOENT`. Currently you are silencing all IOErrors raised by stat that aren't 'No such file or directory'. – Chris Wesseling Apr 30 '14 at 14:19
  • would it be preferable to specify the error number? if e.errno == [2] or is that all the same. In this case I am only checking to see if the file exists so I can either create, or archive old and put in new. I am not sure I understand what other errors I may be silencing with a general solution, as I have written it. – dbell Apr 30 '14 at 15:00

0 Answers0