访问ftp,无非两件事情:upload和download,最近在项目中需要从ftp下载大量文件,然后我就试着去实验自己的ftp操作类,如下(ps:此段有问题,别复制使用,可以参考去试验自己的ftp类!)
import os
from ftplib import ftp
class ftpsync():
def __init__(self, host, usr, psw, log_file):
self.host = host
self.usr = usr
self.psw = psw
self.log_file = log_file
def __connectserver(self):
try:
self.ftp = ftp(self.host)
self.ftp.login(self.usr, self.psw)
self.ftp.set_pasv(false)
return true
except exception:
return false
def __closeserver(self):
try:
self.ftp.quit()
return true
except exception:
return false
def __checksizeequal(self, remotefile, localfile):
try:
remotefilesize = self.ftp.size(remotefile)
localfilesize = os.path.getsize(localfile)
if localfilesize == remotefilesize:
return true
else:
return false
except exception:
return none
def __downloadfile(self, remotefile, localfile):
try:
self.ftp.cwd(os.path.dirname(remotefile))
f = open(localfile, ‘wb’)
remotefilename = ‘retr ‘ + os.path.basename(remotefile)
self.ftp.retrbinary(remotefilename, f.write)
if self.__checksizeequal(remotefile, localfile):
self.log_file.write(‘the file is downloaded successfully to %s’ + ‘\n’ % localfile)
return true
else:
self.log_file.write(‘the localfile %s size is not same with the remotefile’ + ‘\n’ %localfile)
return false
except exception:
return false
def __downloadfolder(self, remotefolder, localfolder):
try:
filelist = []
self.ftp.retrlines(‘nlst’, filelist.append)
for remotefile in filelist:
localfile = os.path.join(localfolder, remotefile)
return self.__downloadfile(remotefile, localfile)
except exception:
return false
def syncfromftp(self, remotefolder, localfolder):
self.__downloadfolder(remotefolder, localfolder)
self.log_file.close()
self.__closeserver()