How can I send StringIO via FTP in python 3?

I want to upload a text string to 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
+5
source share
3 answers

This can lead to confusion in Python 3, especially because tools like this csvwill only write str, but ftplibwill only accept bytes.

You can handle this using io.TextIOWrapper:

import io
import ftplib


file = io.BytesIO()

file_wrapper = io.TextIOWrapper(file, encoding='utf-8')
file_wrapper.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)
+2
source

You can also do it

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)
+1
source

It 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)
0
source

All Articles