tags:

views:

635

answers:

2

So i've followed the docs on this page: http://docs.python.org/library/ftplib.html#ftplib.FTP.retrbinary

And maybe i'm confused just as to what 'retrbinary' does...i'm thinking it retrives a binary file and from there i can open it and write out to that file.

here's the line that is giving me problems...

ftp.retrbinary('RETR temp.txt',open('temp.txt','wb').write)

what i don't understand is i'd like to write out to temp.txt, so i was trying

ftp.retrbinary('RETR temp.txt',open('temp.txt','wb').write('some new txt'))

but i was getting errors, i'm able to make a FTP connection, do pwd(), cwd(), rename(), etc.

p.s. i'm trying to google this as much as possible, thanks!

+1  A: 

It looks like the original code should have worked, if you were trying to download a file from the server. The retrbinary command accepts a function object you specify (that is, the name of the function with no () after it); it is called whenever a piece of data (a binary file) arrives. In this case, it will call the write method of the file you opened. This is slightly different than retrlines, because retrlines will assume the data is a text file, and will convert newline characters appropriately (but corrupt, say, images).

With further reading it looks like you're trying to write to a file on the server. In that case, you'll need to pass a file object (or some other object with a read method that behaves like a file) to be called by the store function:

ftp.storbinary("STOR test.txt", open("file_on_my_computer.txt", "rb"))
Paul Fisher
yes i am trying to write to a file on the server, but now that i think of it that may be the wrong way to go...rather i should just create the file locally then send/upload the file once it has been written/created, this way it should minizie the connection time.
SkyLar
That would be the easiest way to write to a file on the server. Initially, I thought you were trying to download a file from the server. I've updated my answer to clarify what the code you have (in the first block) actually does.
Paul Fisher
A: 

ftp.retrbinary takes second argument as callback function it can be directly write method of file object i.e.open('temp.txt','wb').write but instead you are calling write directly

you may supply your own callback and do whatever you want to do with data

def mywriter(data):
    print data
ftp.retrbinary('RETR temp.txt', mywriter)
Anurag Uniyal