Python直接在FTP中写入创建文件 [英] Python write create file directly in FTP
问题描述
<$>
p $ p>
ftp = FTP('ftp.mysite.com')
ftp.login('un','pw')
ftp.cwd('/')
ftp.storbinary('STOR myfile.html','text to store','rb')
这甚至有可能吗?
非常感谢。
As 文档说:
以二进制传输模式存储文件。 cmd 应该是一个合适的
提供要存储的数据...STOR
命令:STOR文件名
。 file 是一个文件对象(以二进制模式打开),使用大小 blocksize的块中的read()
方法读取,直到EOF
所以,你需要给它一个类似文件的对象, 读取
方法。
字符串不是文件类型的对象,而是 io.BytesIO
是。所以:
pre $ import io
bio = io.BytesIO(b'text to store')
ftp .storbinary('STOR myfile.html',bio)
<另外,请注意,我没有传递
'rb'
参数。对 storbinary
的第三个参数是 blocksize ,并且'rb'
显然不是有效的块大小。 如果您需要使用Python 2.5或更早版本,请参阅Dan Lenski的答案。 b
$ b
如果您需要使用Python 2.6-2.7,并且类文件对象的性能很重要(它不在这里,但在某些情况下可能会出现这种情况),你只关心CPython,使用他的答案,但使用 cStringIO
来代替 StringIO
。 (Plain StringIO
在2.x中速度较慢,并且在$ 3.3之前 io.BytesIO
甚至更慢) p>
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.
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 itsread()
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.)
这篇关于Python直接在FTP中写入创建文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!