簡體   English   中英

嘗試上傳具有unicode內容的XML時,Python ftplib UnicodeEncodeError

[英]Python ftplib UnicodeEncodeError when trying to upload an XML with unicode content

我正在嘗試使用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聲明中使用的字符編碼與用於存儲文件的編碼一致。

我能夠找到解決方案,@ Cairnarvon的注釋部分正確,我正在編碼字符串,但是寫入StringIO實例的字符串中還有其他未編碼的位。 最后,我最終創建了XML位並對其進行了整體編碼。 您可以在下面的pastebin鏈接中看到我的代碼;

http://pastebin.com/GugTLRQJ

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM