我想通过 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
, while 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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)