在python 3中,如何通过FTP发送StringIO?
我想通过FTP上传一个文本字符串作为文件在python 3中,如何通过FTP发送StringIO?,python,python-3.x,ftp,stringio,bytesio,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) 此
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
这在Python3中可能是一个混淆点,特别是因为像
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)
你也可以这样做
binary_file = io.BytesIO()
text_file = io.TextIOWrapper(binary_file)
text_file.write('foo')
text_file.writelines(['bar', 'baz'])
binary_file.seek(0)
ftp.storbinary('STOR foo.txt', binary_file)
在python 3中为我工作
content_json = bytes(json.dumps(content),"utf-8")
with io.StringIO(content_json) as fp:
ftps.storlines("STOR {}".format(filepath), fp)
你能显示完整的堆栈跟踪,这样我们就可以知道是哪一行引起了错误吗?试着把第5行改成fileHandler.write(u“aaa”)
,把第13行改成ftp.storbinary(u“STOR 123.txt”,fileHandler,bufsize)
如果我只做file\u wrapper.seek(0)
,而不是file.seek(0)
,这似乎也行得通,我的文件按预期存储在ftp中,因此可以查找io
流中的任何一个吗@斯蒂芬·富里