尝试上传带有 unicode 内容的 XML 时出现 Python ftplib UnicodeEncodeError

标签 python ftplib python-unicode

我正在尝试使用 ftplib 将包含 unicode 内容的 XML 上传到 FTP 服务器,但是当我尝试使用 storbinary 方法上传时出现以下异常。 XML 数据已正确编码为 un​​icode (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/

相关文章:

python - 捕获由 ftplib 中的连接错误引起的异常

python - 识别 FTP 中的新文件并将其写入 AWS S3

python - 将微符号字符保存在 mongo 集合中

python - 如何打开读写文件并重新创建文件?

python - 使用 Python ftplib 的 FTPS - 需要 session 重用

python - 你如何在 Python 中绘制网格和矩形?

django - verbose_name 或 help_text 中的重音/特殊字符(例如,ñ)?

python - 方向键的unicode?

python - 使用带有 sys.stdout 的 Python 'with' 语句

python - 展开时在 sizer 中为 wx.CollapsiblePane 分配更多的大小