Python ftplib 上传含 Unicode 内容的 XML 时出现 UnicodeEncodeError

2 投票
2 回答
1698 浏览
提问于 2025-04-17 16:55

我正在尝试使用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)

2 个回答

1

你应该以二进制模式打开一个文件,然后把它传给 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声明中使用的字符编码和你存储文件时用的编码是一致的。

0

我找到了解决办法,@Cairnarvon 的评论部分是对的。我确实对字符串进行了编码,但还有其他一些字符串的部分没有被编码。最后,我把整个 XML 部分都创建出来并进行了编码。你可以在下面的链接看到我的代码:

http://pastebin.com/GugTLRQJ

撰写回答