use*_*531 5 python ftp bytesio stringio python-3.x
我想通过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)
Run Code Online (Sandbox Code Playgroud)
此代码返回错误:
TypeError: 'str' does not support the buffer interface
Run Code Online (Sandbox Code Playgroud)
这可能是 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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1689 次 |
| 最近记录: |