我正在尝试使用 ftplib 将包含 unicode 内容的 XML 上传到 FTP 服务器,但是当我尝试使用 storbinary 方法上传时出现以下异常。 XML 数据已正确编码为 unicode (utf-8),我已经确定了这一点,我不确定为什么 storbinary 在上传时试图将其编码为“ascii”。有人可以帮忙吗?
--> 429 ftp.storbinary("STOR file.xml", xml) 430 431 def run(self): /usr/lib/python2.7/ftplib.pyc in storbinary(self, cmd, fp, blocksize, callback, rest) 463 buf = fp.read(blocksize) 464 if not buf: break --> 465 conn.sendall(buf) 466 if callback: callback(buf) 467 conn.close() /usr/lib/python2.7/socket.pyc in meth(name, self, *args) 222 223 def meth(name,self,*args): --> 224 return getattr(self._sock,name)(*args) 225 226 for _m in _socketmethods: UnicodeEncodeError: 'ascii' codec can't encode character u'\xae' in position 3368: ordinal not in range(128)
最佳答案
您应该将以二进制模式打开的文件传递给 ftp.storbinary()
。例如,如果您想将 Unicode 字符串作为 filename
文件上传:
import io
assert isinstance(unicode_string, unicode)
file = io.BytesIO(unicode_string.encode("utf-8"))
ftp.storbinary("STOR filename", file)
如果unicode_string
包含xml;确保 xml 声明中使用的字符编码与您用于存储文件的编码一致。
关于尝试上传带有 unicode 内容的 XML 时出现 Python ftplib UnicodeEncodeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15050506/