Python writes creation file directly to FTP

I want to write text directly to my FTP site from python without saving the temporary file to disk, something like:

ftp = FTP('ftp.mysite.com') ftp.login('un','pw') ftp.cwd('/') ftp.storbinary('STOR myfile.html', 'text to store', 'rb') 

Is it even possible? Thank you very much.

+6
source share
2 answers

As the docs say:

Save the file in binary transfer mode. cmd should be a suitable STOR : "STOR filename" command. file is a file object (opened in binary mode) that is read until the EOF uses the read() method in block size blocks to ensure data is saved ...

So, you need to provide it with a file-like object with the appropriate read method.

The string is not a file-like object, but io.BytesIO . So:

 import io bio = io.BytesIO(b'text to store') ftp.storbinary('STOR myfile.html', bio) 

Also note that I did not pass this argument to 'rb' . The third storbinary parameter storbinary blocked, and 'rb' is obviously not a valid block size.


If you need to work with Python 2.5 or earlier, see Dan Lensky's answer.

And if you need to work with Python 2.6-2.7, and the performance of the file object is important (it is not here, but there are times when it may be), and you only care about CPython, use its answer, but cStringIO instead of StringIO . (Regular StringIO slow at 2.x, and io.BytesIO even slower at 3.3.)

+8
source

Have you tried using a StringIO object that bows like a file, but just a string?

 from ftplib import * import StringIO ftp = FTP('ftp.mysite.com') ftp.login('un','pw') ftp.cwd('/') ftp.storbinary('STOR myfile.html', StringIO.StringIO('text to store')) 

EDIT: @abarnert answer is Python3 equivalent. Mine is a version of Python2.

+5
source

Source: https://habr.com/ru/post/975007/


All Articles