python - 如何在 python 3 中通过 FTP 发送 StringIO?

标签 python python-3.x ftp stringio bytesio

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

最佳答案

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

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

关于python - 如何在 python 3 中通过 FTP 发送 StringIO?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30449269/

相关文章:

python - pil(枕头)图像中的 channel 数

python - 使用 Python 计算数据框中唯一单词的数量

python - Ruby pack ('H*' ) 在 Python 中等效

python-3.x - 调度 Airflow TaskGroup抛出AttributeError

java - 蜂窝数据上的 FTP 显式失败

java - 限制 Apache MINA FtpServer 上的可访问文件和目录

python - Beautiful Soup 返回不完整的 HTML 脚本

Python - 将二维列表中的值除以单个值的简便快捷方法

python - Wx.stc.StyledTextCtrl 滚动条

python - 使用FTP忽略python中的异常