一、FTP上传下载代码
from ftplib import FTPdef ftpconnect(host, port, username, password):ftp = FTP()ftp.set_debuglevel(2)ftp.connect(host, port)ftp.login(username, password)return ftpdef downloadfile(ftp, remotepath, localpath):# 从ftp下载文件bufsize = 1024fp = open(localpath, 'wb')ftp.retrbinary('RETR ' + remotepath, fp.write, bufsize)ftp.set_debuglevel(0)fp.close()def uploadfile(ftp, localpath, remotepath):# 从本地上传文件到ftpbufsize = 1024fp = open(localpath, 'rb')ftp.storbinary('STOR ' + remotepath, fp, bufsize)ftp.set_debuglevel(0)fp.close()if __name__ == "__main__":ftp = ftpconnect("192.168.100.22", 10021, "medical", "medical002")ftp.pwd() # 获取当前位置uploadfile(ftp, "/home/rxf/other/PlatServerTest/2.jpg", "D:/download/Ranxiangfei/2.jpg")downloadfile(ftp,"/car/zjyd_car_rg_call_20190308.txt", "E:/re_buy_car/test/files/zjyd_car_rg_call_20190308.txt")ftp.quit()
二、问题报错
使用ftplib上传文件的时候,遇到包含中文的文件名报错UnicodeEncodeError: 'latin-1' codec can't encode charactersin position 4-5: ordinal not in range(256)
解决方案:
方案1:更改配置
更改ftplib.py里
encoding ='latin-1'
为
encoding ='utf-8'
ftplib.py文件一般在python安装目录的Lib文件夹下
方案2:不用中文
用英文!