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