4

I want to upload a file on an ftp site if the file is not present. This is a task of a more complex application, but it's not important in this case. My idea is to check if the file is present with the FTP.size(filename) method and if the error is 550 (The system cannot find the file specified) upload the file.

My (not working) code:

from ftplib import *
ftp = FTP("ftp.test.com", "user", "password")
try:
    ftp.size("123.zip")
except ftplib.all_errors, e:
    if e.errno == 550:
        print "UPLOAD"
    else:
        print str(e)

The error returned is

Traceback (most recent call last):
  File "<pyshell#106>", line 4, in <module>
    if e.errno == 550:
AttributeError: 'error_perm' object has no attribute 'errno'

or if a temporary error occured:

AttributeError: 'error_temp' object has no attribute 'errno'

The only solution I found to manage the return code was this:

except ftplib.all_errors, e:
if str(e.args[0]).split(" ", 1)[0] == "550":
        print "UPLOAD"
    else:
        print str(e)

but I suppose there is a best solution, because this work only if the error number is the first word in the exception message.

Thank you in advance!

BigDie
  • 51
  • 3
  • This code works just fine on my computer. Are you sure you are using the right version of Python? I'm running 2.7. – drRoflol Mar 27 '14 at 12:20

2 Answers2

1

I don't know exactly the properties of that error, so what you can do is to print dir(e) when the except clause activates. Then you will see all the properties of the error. One that fails almost never as a flag is "error.message", which is a string, so you can build the if clause with that.

You would end with something like

try:
    ftp.size("123.zip")
except ftplib.all_errors as e:
    if e.message == 'message of the error'
        print 'UPLOAD'
    else:
        print str(e)

by the way, message is one thing that you get when str(e) is executed.

chuse
  • 373
  • 3
  • 18
0

Perhaps this helps, it's from the documentation for ftplib.

Note that the SIZE command is not standardized, but is supported by many common server implementations.

Link here

Try using another way to find out if the file excists.

drRoflol
  • 305
  • 4
  • 13