SkyLar
SkyLar

Reputation: 93

writing to a file via FTP in python

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!

Upvotes: 1

Views: 7379

Answers (2)

Paul Fisher
Paul Fisher

Reputation: 9666

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"))

Upvotes: 3

Anurag Uniyal
Anurag Uniyal

Reputation: 88845

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)

Upvotes: 0

Related Questions