如何在python 3中通过FTP发送StringIO? [英] How can I send a StringIO via FTP in python 3?

查看:178
本文介绍了如何在python 3中通过FTP发送StringIO?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过FTP将文本字符串作为文件上传.

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)

此代码返回错误:

TypeError: 'str' does not support the buffer interface

推荐答案

这可能是python 3的一个困惑点,尤其是因为像csv这样的工具只会写str,而ftplib只接受bytes.

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.

您可以通过使用io.TextIOWrapper来解决此问题:

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)

这篇关于如何在python 3中通过FTP发送StringIO?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆