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 Sel f.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:ret Urn False def __closeserver (self): Try:self.ftp.quit () return True except Exception:return Fals E def __checksizeequal (self, RemoteFile, localfile): Try:remotefilesize = Self.ftp.size (remotefile) Loca Lfilesize = Os.path.getsize (localfile) if localfilesize = = Remotefilesize:return True else:retur n 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 (remotefi Le) 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:retur n False def __downloadfolder (self, Remotefolder, localfolder): Try:filelist = [] Self.ftp.retrlines (' NLS T ', filelist.append) for remotefile in filelist:localfile = Os.path.join (Localfolder, RemoteFile) Retu RN Self.__downloadfile (remotefile, localfile) except Exception:return False def syncfromftp (self, Remotefolde R, Localfolder): Self.__downloadfolder (Remotefolder, Localfolder) self.log_file.close () Self.__closeserver ()