Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error for ftplib.cwd: UnicodeEncodeError: 'latin-1' codec can't encode characters

There are many posts about 'latin-1' codec , however those answers can't solve my problem, maybe it's my question, I am just a rookie to learn Python, somewhat. When I used cwd(dirname) to change directory of FTP site, the unicodeerror occurred. Note that dirname included Chinese characters, obviously, those characters caused this error. I made some encoding and decoding according to the suggestions in the past posts, but it didn't work. Could someone give me some advice how to repair this error and make cwd work?

Some codes:

file = 'myhongze.jpg'
dirname = './项目成员资料/zgcao/test-python/'
site = '***.***.***.***'
user = ('zhigang',getpass('Input Pwd:'))    
ftp = FTP(site)
ftp.login(*user)            
ftp.cwd(dirname)# throw exception

Some tests:

u'./项目成员资料/zgcao/test-python/'.encode('utf-8')

Output:

b'./\xe9\xa1\xb9\xe7\x9b\xae\xe6\x88\x90\xe5\x91\x98\xe8\xb5\x84\xe6\x96\x99/zgcao/test-python/'

u'./项目成员资料/zgcao/test-python/'.encode('utf-8').decode('cp1252')

Output:

UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 10: character maps to <undefined>

u'./项目成员资料/zgcao/test-python/'.encode('utf-8').decode('latin-1')

Output:

'./项ç\x9b®æ\x88\x90å\x91\x98èµ\x84æ\x96\x99/zgcao/test-python/'
Using the result of decode('latin-1'), the cwd can't still work.

It is noted that 项目成员资料 is showed as ÏîÄ¿×é³ÉԱ˽ÈË¿Õ¼ä when I used retrlines('LIST').

like image 663
zhigang Avatar asked Nov 08 '22 21:11

zhigang


1 Answers

No need to edit ftplib source code. Just set ftp.encoding property in your code:

ftp.encoding = "UTF-8"
ftp.cwd(dirname)

A similar question, about FTP output, rather then input:
List files with UTF-8 characters in the name in Python ftplib

like image 69
Martin Prikryl Avatar answered Nov 14 '22 23:11

Martin Prikryl