https://www.cnblogs.com/wangziyi0513/p/11077323.html
参考原始代码:
修改了一下:
许多网友问中文路径乱码怎么办,我觉得应该讲中文路径转码后再发送。
ftpath = '/home/omcr/文档/{}'.format(y).encode('utf-8').decode('latin-1')
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/4/12 22:00
# @Author : zengsk in HoHai
# edited by wh
'''
FTP批量下载数据
'''
import os
import sys
from ftplib import FTP
import datetime
class FtpDownloadCls:
def __init__(self, ftpserver, port, usrname, pwd, encode1, decode1):
self.ftpserver = ftpserver # ftp主机IP
self.port = port # ftp端口
self.usrname = usrname # 登陆用户名
self.pwd = pwd # 登陆密码
self.ftp = self.ftpConnect()
# 用于中文编码解码,
self.encode1 = encode1
self.decode1 = decode1
# ftp连接
def ftpConnect(self):
ftp = FTP()
try:
ftp.connect(self.ftpserver, self.port)
ftp.login(self.usrname, self.pwd)
# python ftplib 默认的编码方式是latin-1
self.encode1 = ftp.encoding
except:
raise IOError('\n FTP login failed!!!')
else:
print(ftp.getwelcome())
print('\n+------- FTP connection successful!!! --------+\n')
return ftp
# 单个文件下载到本地
def downloadFile(self, ftpfile, localfile):
bufsize = 1024
# 要在本地正确的显示中文,需要先通过latin-1编码成unicode,在解码成utf-8或GBK
with open(localfile.encode(self.encode1).decode(self.decode1), 'wb') as fid:
self.ftp.retrbinary('RETR {0}'.format(ftpfile), fid.write, bufsize)
return True
# 下载整个目录下的文件,包括子目录文件
def downloadFiles(self, ftpath, localpath):
print('FTP PATH: {0}'.format(ftpath))
if not os.path.exists(localpath):
os.makedirs(localpath)
self.ftp.cwd(ftpath)
print('\n+----------- downloading!!! -----------+\n')
for i, file in enumerate(self.ftp.nlst()):
print('{0} <> {1}'.format(i, file))
local = os.path.join(localpath, file)
if os.path.isdir(file): # 判断是否为子目录
if not os.path.exists(local):
os.makedirs(local)
self.downloadFiles(file, local)
else:
self.downloadFile(file, local)
self.ftp.cwd('..')
return True
# 退出FTP连接
def ftpDisConnect(self):
self.ftp.quit()
# 程序入口
if __name__ == '__main__':
yesterday = (datetime.datetime.now() - datetime.timedelta(days = 1))
y = yesterday.strftime("%Y%m%d")
# 输入参数
ftpserver = '10.20.20.1' # ftp主机IP
port = 21 # ftp端口
usrname = 'omcr' # 登陆用户名
pwd = 'abcd.1' # 登陆密码
#ftpath = '/export/home/omcr/UMS8800_WKM_TDL_V3.0.0_26_20171013/LTE_WKM/webapps/WKMService/reportfile/计划报表/20190623/' # 远程文件夹
# 想要将路径中的中文正确发送到ftp服务器,需要先通过本地编码utf-8转换为unicode,在编码为latin-1,这样才能被ftplib模块正确发送给ftp服务器,虽然发送过去的中文编码是乱的
# 但服务器可以识别
ftpath = '/home/omcr/文档/{}'.format(y).encode('utf-8').decode('latin-1')
localpath = 'D:/EC/data/{}'.format(y) # 本地文件夹(不要使用中文)
Ftp = FtpDownloadCls(ftpserver, port, usrname, pwd, 'latin-1', 'utf-8')
Ftp.downloadFiles(ftpath, localpath)
Ftp.ftpDisConnect()
print("\n+-------- OK!!! --------+\n")
# 删除多余文件
dirPath = r'D:/EC/data'
x = ''
for f in os.listdir(dirPath):
if not x in f:
os.remove(os.path.join(dirPath, f))