python----ftplib中遇到中文路径错误问题
python----ftplib中遇到中文路径错误问题
笔者在写一个简易的ftp程序的时候。
遇到返回提示说找不到FTP上的路径。
但是路径肯定时没错的。
而且当路径变成普通的不含中文的路径的时候,就是正常的。
下面是笔者的代码
#!/usr/bin/python3 #-*- coding: utf-8 -*- from ftplib import FTP import sys,time,os,hashlib #定义时间 sys_time = time.time() sys_time_array = time.localtime(sys_time) current_time = time.strftime("%Y-%m-%d %H:%M:%S:",sys_time_array) class ftp(): def __init__(self,ip,port,user,password): self.ip = ip self.port = port self.user = user self.password = password #----------------定义下载模块-----------------# def ftp_download(self,remote_path,local_path): ftp = FTP() try: ftp.connect(self.ip,self.port) ftp.login(self.user,self.password) except: print('connect to FTP server failed!!!') else: file_list = ftp.nlst(remote_path) key = os.path.exists(local_path) if str(key) == 'True': pass else: os.makedirs(local_path) print("downloading!!!") try: for file in file_list: bufsize = 1024 file_name = file.split('/')[-1] local_file = open(local_path+file_name,'wb') ftp.retrbinary('RETR %s'%(file),local_file.write,bufsize) ftp.set_debuglevel(0) local_file.close() except: print("%s %s download failed!!!" %(current_time,remote_path)) else: print("%s %s download successfully!!!" %(current_time,remote_path)) #----------------定义上传模块-----------------# def ftp_upload(self,remote_path,local_path): ftp = FTP() try: ftp.connect(self.ip,self.port) ftp.login(self.user,self.password) except: print('connect to FTP server failed!!!') else: try: ftp.mkd(remote_path) except: pass try: file_list = os.walk(local_path) for root,dirs,files in file_list: for file in files: local_file = local_path + file remote_file = remote_path + file bufsize = 1024 fp = open(local_file,'rb') ftp.storbinary('STOR ' + remote_file, fp, bufsize) fp.close() except: print("%s %s upload failed!!!" %(current_time,local_path)) else: print("%s %s upload successfully!!!" %(current_time,local_path))
查阅了很多网上的资料,发现在python自带的模块ftplib.py中定义了编码模式
vim /usr/local/python3/lib/python3.6/ftplib.py
初始的编码模式是
coding = 'latin-1'
后来笔者把他改成了‘utf-8’
但是问题并不能解决
最后笔者狠下心来把他改成了
encoding = "GB2312"
问题迎刃而解
这里的重点应该是了解FTP服务器究竟是搭建在什么机子上,然后需要把ftplib.py中的编码模式改成对应的编码模式。