How can I send a StringIO via FTP in python 3?

2019-06-27 12:34发布

I want to upload a text string as a file via FTP.

import ftplib
from io import StringIO

file = StringIO()
file.write("aaa")
file.seek(0)


with ftplib.FTP() as ftp:
    ftp.connect("192.168.1.104", 2121)
    ftp.login("ftp", "ftp123")
    ftp.storbinary("STOR 123.txt", file)

This code returns an error:

TypeError: 'str' does not support the buffer interface

3条回答
\"骚年 ilove
2楼-- · 2019-06-27 13:02

This can be a point of confusion in python 3, especially since tools like csv will only write str, while ftplib will only accept bytes.

One way around this problem is to extend io.BytesIO to encode your str to bytes before writing:

import io
import ftplib

class StrToBytesIO(io.BytesIO):

    def write(self, s, encoding='utf-8'):
        return super().write(s.encode(encoding))

file = StrToBytesIO()
file.write("aaa")
file.seek(0)

with ftplib.FTP() as ftp:
    ftp.connect(host="192.168.1.104", port=2121)
    ftp.login(user="ftp", passwd="ftp123")

    ftp.storbinary("STOR 123.txt", file)
查看更多
时光不老,我们不散
3楼-- · 2019-06-27 13:15

You can do this as well

binary_file = io.BytesIO()
text_file = io.TextIOWrapper(binary_file)

text_file.write('foo')
text_file.writelines(['bar', 'baz'])

binary_file.seek(0)
ftp.storbinary('STOR foo.txt', binary_file)
查看更多
Melony?
4楼-- · 2019-06-27 13:24

Works for me in python 3.

content_json = bytes(json.dumps(content),"utf-8")
with io.StringIO(content_json) as fp:
    ftps.storlines("STOR {}".format(filepath), fp)
查看更多
登录 后发表回答