【问题标题】:How can I send a StringIO via FTP in python 3?如何在 python 3 中通过 FTP 发送 StringIO?
【发布时间】:2015-08-07 13:54:40
【问题描述】:

我想通过 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)

此代码返回错误:

TypeError: 'str' does not support the buffer interface

【问题讨论】:

  • 您能否显示完整的堆栈跟踪,以便我们知道是哪一行导致了错误?
  • 尝试将 line 5 更改为 fileHandler.write(u"aaa") 并将 line 13 更改为 ftp.storbinary(u"STOR 123.txt",fileHandler,bufsize)

标签: python python-3.x ftp stringio bytesio


【解决方案1】:

这可能是 python 3 中的一个混淆点,特别是因为像csv 这样的工具只会写str,而ftplib 只会接受bytes

你可以使用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)

【讨论】:

  • 如果我只做file_wrapper.seek(0) 而不是file.seek(0),这似乎也有效,我的文件按我的预期存储在ftp 中,所以可以寻找io 流中的任何一个吗? @stephen-fuhry
【解决方案2】:

在 python 3 中为我工作。

content_json = bytes(json.dumps(content),"utf-8")
with io.StringIO(content_json) as fp:
    ftps.storlines("STOR {}".format(filepath), fp)

【讨论】:

    【解决方案3】:

    你也可以这样做

    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)
    

    【讨论】: