Need help understanding this error, and how to eliminate it. Using Python 3.3.

I'm trying to define a function that takes two arguments and then constructs the proper arguments for a call to the ftblib.storbinary method.

Here's my code:

    from ftplib import FTP_TLS

    ftps = FTP_TLS('xxxxxx', user='xxxx', passwd='xxxx')
    ftps.prot_p()
    ftps.set_pasv(False)


    ## Function for sending file ##
    def fileup (destname, sourcepath):
        outbound = 'STOR ' + destname 
        filesrc = 'open(\"'+sourcepath +'\", \'rb\')'
        print('outbound = '+ outbound)
        print('filesrc = '+ filesrc)
        print(  outbound + '        ' + filesrc)
        ftps.storbinary(outbound, filesrc, 8192)

    fileup('textgetFUNC01.txt', 'C:/inetpub/ftproot/textget1122.txt')


    ftps.close()

It creates a file (but file is 0kB) on the destination machine and throws this error:

Traceback (most recent call last):
  File "C:/pathto/funky.py", line 18, in <module>
    fileup('textgetFUNC01.txt', 'C:/inetpub/ftproot/textget1122.txt')
  File "C:/pathto/funky.py", line 16, in fileup
    ftps.storbinary(outbound, filesrc, 8192)
  File "C:\Python33\lib\ftplib.py", line 789, in storbinary
    buf = fp.read(blocksize)
AttributeError: 'str' object has no attribute 'read'

However if I comment out the function and just run this statement in its place, I get a clean execution ( file is transferred, new file with appropriate content is created on destination machine and no errors generated).

ftps.storbinary('STOR textgetFUNC01.txt', open("C:/inetpub/ftproot/textget1122.txt", 'rb'), 8192)

As far as I can tell, this is the exact same argument list I am building with my function and passing to storbinary within my function.

I've looked at line 789 in ftplib.py but don't understand what it is trying to do. So I'd like to figure out how to make my function work, and stop generating the AttributeError. What am I doing wrong in building the argument list within my function? Why does it work when I call storbinary directly , but not when I do it from my function when I am building the same argument list?

I suspect I am not, in fact, building the same argument list within the function, but all my debugging (the print statements) appear to confirm that I am.

Any suggestions?

The obvious error is that the file argument in storbinary() must be an open file object instead of a string. Try

with open(sourcepath, 'rb') as ifh:
    ftps.storbinary(outbound, ifh, 8192)

Thank you very much. I see now I was building a string, instead of creating the object. All working now.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.