This article describes a Python implementation method that supports directory FTP upload and download files. Share to everyone for your reference. Specific as follows:
The program supports FTP uploads to download files and directories, for Windows and Linux platforms.
#!/usr/bin/env python#-*-coding:utf-8-*-import ftplibimport osimport sysclass Ftpsync (object): conn = Ftplib. FTP () def __init__ (self,host,port=21): Self.conn.connect (host,port) def login (Self,username,password): Sel F.conn.login (Username,password) SELF.CONN.SET_PASV (False) print Self.conn.welcome def test (Self,ftp_path): Print Ftp_path print Self._is_ftp_dir (ftp_path) #print self.conn.nlst (Ftp_path) #self. Conn.retrlines (' LIST./a/b ') #ftp_parent_path = Os.path.dirname (ftp_path) #ftp_dir_name = Os.path.basename (Ftp_path) #print Ftp_parent_path # Print Ftp_dir_name def _is_ftp_file (self,ftp_path): Try:if Ftp_path in Self.conn.nlst (Os.path.dirname (Ftp_path)) : Return True Else:return false except Ftplib.error_perm,e:return false def _ftp_list (self, Line): List = Line.split (") if self.ftp_dir_name==list[-1] and List[0].startswith (' d '): Self._is_dir = True def _is_ftp_dir (Self,ftp_path): Ftp_path = Ftp_path.rstrip ('/') Ftp_parent_path = Os.path.dirname (ftp_path) self.ftp_dir_name = Os.path.basename ( Ftp_path) Self._is_dir = False if Ftp_path = = '. ' or ftp_path== './' or ftp_path== ': Self._is_dir = True El SE: #this ues callback function, that would change _is_dir value Try:self.conn.retrlines (' LIST%s '%ftp_p arent_path,self._ftp_list) except Ftplib.error_perm,e:return self._is_dir return Self._is_dir def get _file (self,ftp_path,local_path= '): Ftp_path = Ftp_path.rstrip ('/') if Self._is_ftp_file (Ftp_path): File_n Ame = Os.path.basename (ftp_path) #如果本地路径是目录, download the file to the directory if Os.path.isdir (local_path): File_handler = open (OS . Path.join (Local_path,file_name), ' WB ') self.conn.retrbinary ("RETR%s"% (Ftp_path), file_handler.write) fi Le_handler.close () #如果本地路径不是目录, but the upper directory exists, follow the local path filename as the file name of the download Elif Os.path.isdir (Os.path.dirname (Local_path)): File_handler = open (Local_path, ' WB ') self.conn.retrbinary ("RETR%s"% (Ftp_path), File_handler.write) File_handler.close () #如果本地路径不是目录, and the upper directory does not exist, exit Else:print ' eroor:the dir:%s is not exist '%os.path.dirname (Local_path) Else: print ' eroor:the ftp file:%s is not exist '%ftp_path def put_file (self,local_path,ftp_path= '. '): Ftp_path = Ftp_pa Th.rstrip ('/') if Os.path.isfile (local_path): File_handler = open (Local_path, "R") Local_file_na me = Os.path.basename (local_path) #如果远程路径是个目录, upload file to this directory, file name is unchanged if Self._is_ftp_dir (Ftp_path): self.conn.s Torbinary (' STOR%s '%os.path.join (ftp_path,local_file_name), File_handler) #如果远程路径的上层是个目录, upload file, file name according to the given name Elif SE Lf._is_ftp_dir (Os.path.dirname (Ftp_path)): print ' STOR%s '%ftp_path self.conn.storbinary (' STOR%s '% Ftp_path, File_handler) #如果远程路径不是目录, and the directory on the previous level does not exist, prompting for a given remote path error else:print ' eroor:the FTP path:%s is Error '%ftp_path fIle_handler.close () Else:print ' error:the file:%s is not exist '%local_path def get_dir (Self,ftp_path,local_path = '. ', begin=true): Ftp_path = Ftp_path.rstrip ('/') #当ftp目录存在时下载 if Self._is_ftp_dir (ftp_path): #如果下载到本地当 Pre-directory and create a directory #下载初始化: If the given local path does not exist, it needs to be created, and the FTP directory is stored in the given local directory. #ftp目录下文件存放的路径为local_path =local_path+os.path.basename (Ftp_path) #例如: FTP Folder A is downloaded to a local A/b directory, and the files under FTP a directory are downloaded to a local A/b /a directory if begin:if not Os.path.isdir (Local_path): Os.makedirs (Local_path) LOCAL_PATH=OS.PATH.J Oin (Local_path,os.path.basename (Ftp_path)) #如果本地目录不存在, create directory if not Os.path.isdir (Local_path): Os.makedirs (Local_path) #进入ftp目录, start recursive query self.conn.cwd (ftp_path) ftp_files = Self.conn.nlst () for file in Ftp_file S:local_file = Os.path.join (local_path, file) #如果file The FTP path is the directory and recursively uploads the directory (the flag that does not need to initialize begin is modified to false) #如果 File ftp path is files upload file directly if Self._is_ftp_dir (file): Self.get_dir (File,locAl_file,false) Else:self.get_file (file,local_file) #如果当前ftp目录文件已经遍历完毕返回上一层目录 self.conn.cwd (".. ") return Else:print ' error:the dir:%s is not exist '%ftp_path return def put_dir (self,local_path,ftp _path= '. ', begin=true): Ftp_path = Ftp_path.rstrip ('/') #当本地目录存在时上传 if Os.path.isdir (local_path): #上传初始 If the given FTP path does not exist, it needs to be created, and the local directory is stored in the given FTP directory. #本地目录下文件存放的路径为ftp_path =ftp_path+os.path.basename (Local_path) #例如: Uploads the local folder A to the FTP A/b directory, the files in the local a directory will be uploaded to the ftp a/b/ A directory under if Begin:if not Self._is_ftp_dir (Ftp_path): SELF.CONN.MKD (Ftp_path) Ftp_path=os. Path.join (Ftp_path,os.path.basename (Local_path)) #如果ftp路径不是目录, create the directory if not Self._is_ftp_dir (Ftp_path): SELF.CONN.MKD (Ftp_path) #进入本地目录, start recursive query Os.chdir (local_path) local_files = Os.listdir ('. ') For file in Local_files: #如果file本地路径是目录则递归上传目录 (the flag that does not need to initialize begin is modified to false) #如果file本地路径是文件则直接上传文件 If Os.path.isdir (file): Ftp_path=os.path.join (ftp_path,file) Self.put_dir (file,ftp_path,f Alse) Else:self.put_file (File,ftp_path) #如果当前本地目录文件已经遍历完毕返回上一层目录 Os.chdir ("..") Else:print ' error:the dir:%s is not exist '%local_path returnif __name__ = = ' __main__ ': FTP = Ftpsync (' 192.168 .1.110 ') ftp.login (' Test ', ' test ') #上传文件, do not rename the #ftp. Put_file (' 111.txt ', ' A/b ') #上传文件, rename #ftp. Put_file (' 111.txt ', ' A/ 112.txt ') #下载文件, do not rename the #ftp. Get_file ('/a/111.txt ', R ' d:\\ ') #下载文件, rename the #ftp. Get_file ('/a/111.txt ', R ' D:\112.txt ') # Download to a folder that already exists #ftp. Get_dir (' a/b/c ', R ' d:\\a ') #下载到不存在的文件夹 #ftp. Get_dir (' a/b/c ', R ' D:\\aa ') #上传到已经存在的文件夹 ftp.put_dir (' B ') , ' a ') #上传到不存在的文件夹 ftp.put_dir (' B ', ' aa/b/')
Hopefully this article will help you with Python programming.