Python write create file directly in FTP

2019-02-06 18:58发布

问题:

I am looking to write a text directly to my FTP site from python without storing a temp file on disk, something like:

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

is this even possible? Thank you very much.

回答1:

As the docs say:

Store a file in binary transfer mode. cmd should be an appropriate STOR command: "STOR filename". file is a file object (opened in binary mode) which is read until EOF using its read() method in blocks of size blocksize to provide the data to be stored…

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

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

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

Also, notice that I didn't pass that 'rb' argument. The third parameter to storbinary is blocksize, and 'rb' is obviously not a valid block size.


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

And if you need to work with Python 2.6-2.7, and performance of the file-like object is important (it isn't here, but there are some cases where it might be), and you only care about CPython, use his answer but with cStringIO in place of StringIO. (Plain StringIO is slow in 2.x, and io.BytesIO is even slower before around 3.3.)



回答2:

Have you tried using a StringIO object, which quacks like a file but is 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's answer is the Python3 equivalent. Mine is the Python2 version.



标签: python ftp