Python implementation to support directory FTP upload download file method

Source: Internet
Author: User
Tags ftp ftp file join

This article describes the Python implementation to support directory FTP upload download file method. Share to everyone for your reference. Specifically as follows:

This program supports FTP uploads to download files and directories, and applies to Windows and Linux platforms.

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26-27--28 29---30 31--32 33 34 35 36 37 38-39 40 41 42 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 5, 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 11 9 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148-149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 #!/usr/bin/env python #-*-coding:utf-8-*-import ftplib import OS import sys class Ftpsync (object): conn = Ftplib. FTP () def __init__ (self,host,port=21): Self.conn.connect (host,port) def login (Self,username,password): Self.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 Else: #this ues callback function, that'll change _is_dir value Try:self.conn.retrlines (' LIST%s '%ftp_parent_pat h,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_name = Os.path.basename (ftp_path) # If the local path is a directory, 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) File_handler.close () #如果本地路径不是目录, but the upper directory exists, Elif Os.path.isdir (Os.path.dirname (Local_path)) by the filename of the local path as the downloaded file name: 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_path.rstrip ('/') If Os.path.isfile (local_path): File_handler = open (Local_path, "r") Local_file_name = Os.path.basename (Local_path) #如果远 Path is a directory, then upload files to this directory, filename unchanged if Self._is_ftp_dir (Ftp_path): Self.conn.storbinary (' STOR%s '%os.path.join (ftp_path,local _file_name), File_handler) #如果远程路径的上层是个目录, then upload files, file names according to the given name Elif Self._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, prompts 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 ' are 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): #如果下载到本地当前目录下, and create a directory #下载初始化: If the given local path does not exist, the FTP directory is stored in the given local directory. #ftp目录下文件存放的路径为local_path =local_path+os.path.basename (ftp_path) #例如: Download ftp folder A to a local A/b directory, thenFiles in the FTP a directory are downloaded to the local a/b/a directory if begin:if not Os.path.isdir (Local_path): Os.makedirs (Local_path) local_path= Os.path.join (Local_path,os.path.basename (Ftp_path)) #如果本地目录不存在, create a directory if not Os.path.isdir (Local_path): Os.makedirs ( Local_path) #进入ftp目录, start the recursive query self.conn.cwd (ftp_path) ftp_files = Self.conn.nlst () for file in Ftp_files:local_file = OS.PA Th.join (Local_path, file) #如果file FTP path is a directory that recursively uploads the directory (the flag that does not need to initialize begin is modified to false) #如果file The FTP path is a file that uploads the 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 are not exist '%ftp_path return   def put_dir (Self,local_pa Th,ftp_path= '. ', begin=true): Ftp_path = Ftp_path.rstrip ('/') #当本地目录存在时上传 if Os.path.isdir (local_path): # Upload initialization: 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) #例如: Upload a local folder A to the FTP A/b directory, then the local a directory of files will be uploaded ftp a/b/ A directory 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 a 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 Again is modified to false) #如果file本地路径是文件则直接上传文件 if Os.path.isdir (file ): Ftp_path=os.path.join (ftp_path,file) self.put_dir (file,ftp_path,false) Else:self.put_file (File,ftp_path) # If the current local directory file has been traversed, return to the previous level directory Os.chdir ("..") Else:print ' error:the dir:%s are not exist '%local_path ' returns if __name__ = ' __ Main__ ': FTP = Ftpsync (' 192.168.1.110 ') ftp.login (' Test ', ' test ') #上传文件, do not rename #ftp. Put_file (' 111.txt ', ' A/b ') #上传文件, renaming # Ftp.put_file (' 111.txt ', ' a/112.txt ') #下载文件, do not rename #ftp. Get_file ('/a/111.txt ', R ' D: ') #下载文件, rename #ftp. Get_file ('/a/111. TXT ', R ' d:112.txt ') #下载到已经存在的文件夹 #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/')

I hope this article will help you with your Python programming.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.