python在ftp里新建文件夹_Python直接在FTP中写入创建文件

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.

解决方案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.)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值