8

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
Stephen Fuhry
  • 12,624
  • 6
  • 56
  • 55
user1021531
  • 487
  • 1
  • 7
  • 16

3 Answers3

6

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)
Stephen Fuhry
  • 12,624
  • 6
  • 56
  • 55
  • this also seems to work if I only do `file_wrapper.seek(0)` instead of `file.seek(0)`, my file was stored in ftp as I expected it, so can either of the `io` stream be seeked? @stephen-fuhry – python_user Jan 21 '21 at 17:00
1

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)
haki
  • 9,389
  • 15
  • 62
  • 110
1

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)
  • `with io.BytesIO(content_json)` and not StringIO : you cannot store bytes in StringIO. With this correction done, your suggestion works fine – Dysmas Dec 28 '22 at 20:17
  • for the reverse process (get StringIO via FTP) see https://stackoverflow.com/questions/11208957/is-it-possible-to-read-ftp-files-without-writing-them-using-python/74949100#74949100 – Dysmas Dec 29 '22 at 09:09