在编写一个自动下载文件的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出错问题。