Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 512
user1021531 Avatar asked May 26 '15 04:05

user1021531


1 Answers

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.

You can deal with this is by 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)
like image 105
Stephen Fuhry Avatar answered Sep 22 '22 14:09

Stephen Fuhry