在編寫一個自動下載文件的ftp程序時出現兩個錯誤:
1、print(ftp.dir('/'))時,控制檯中文輸出亂碼
2、執行下載含中文的文件(路徑)時,出UnicodeEncodeError: 'latin-1'錯
原因:ftplib 的默認編碼方式爲:'latin-1'
解決辦法:修改ftplib的編碼方式爲‘GB2312’
步驟:
1、進入python的安裝目錄,E:\Python\Python36\Lib,在Lib目錄裏找到ftplib.py文件
2、編輯ftplib.py,查找:encoding = "latin-1"
3、修改"latin-1"爲"GB2312",保存
class FTP:
'''An FTP client class.
To create a connection, call the class using these arguments:
host, user, passwd, acct, timeout
The first four arguments are all strings, and have default value ''.
timeout must be numeric and defaults to None if not passed,
meaning that no timeout will be set on any ftp socket(s)
If a timeout is passed, then this is now the default timeout for all ftp
socket operations for this instance.
Then use self.connect() with optional host and port argument.
To download a file, use ftp.retrlines('RETR ' + filename),
or ftp.retrbinary() with slightly different arguments.
To upload a file, use ftp.storlines() or ftp.storbinary(),
which have an open file as argument (see their definitions
below for details).
The download/upload functions first issue appropriate TYPE
and PORT or PASV commands.
'''
debugging = 0
host = ''
port = FTP_PORT
maxline = MAXLINE
sock = None
file = None
welcome = None
passiveserver = 1
encoding = "GB2312"
#encoding = "latin-1" 原來默認是"latin-1",修改爲"GB2312"
再次運行python,完美解決中文亂碼及encode出錯問題。