Access to FTP, nothing more than two things: upload and download, recently in the project need to download a large number of files from FTP, and then I tried to experiment with their own FTP operation class, as follows (PS: This paragraph has a problem, do not copy the use, you can refer to test their own FTP class!) )
Import osfrom 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): TR Y: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 __checksizeequ Al (Self, RemoteFile, localfile): Try:remotefilesize = Self.ftp.size (remotefile) localfilesiz E = os.path.getsize (localfile) if localfilesize = = Remotefilesize:return True Else: return False except Exception:return None def __downloadfile (self, Remotefi Le, 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 s Ize is isn't same with the remotefile ' + ' \ n '%localfile) return False except Exception:re Turn False def __downloadfolder (self, Remotefolder, localfolder): Try:filelist = [] Self.ftp.retrlines (' NLST ', filelist.append) for remotefile in filelist:localfile = Os.path.joi N (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 ()