Download the implementation code of the FTP folder through python

Source: Internet
Author: User

Copy codeThe Code is as follows: #-*-encoding: utf8 -*-
Import OS
Import sys
Import ftplib
Class FTPSync (object ):
Def _ init _ (self ):
Self. conn = ftplib. FTP ('10. 22.33.46 ', 'user', 'pass ')
Self. conn. cwd ('/') # remote FTP directory
OS. chdir ('/data/') # local download directory
Def get_dirs_files (self ):
U''' to get the current directory and file, and put it in the dir_res list '''
Dir_res = []
Self. conn. dir ('.', dir_res.append)
Files = [f. split (None, 8) [-1] for f in dir_res if f. startswith ('-')]
Dirs = [f. split (None, 8) [-1] for f in dir_res if f. startswith ('D')]
Return (files, dirs)
Def walk (self, next_dir ):
Print 'walking to', next_dir
Self. conn. cwd (next_dir)
Try:
OS. mkdir (next_dir)
Failed t OSError:
Pass
OS. chdir (next_dir)
Ftp_curr_dir = self. conn. pwd ()
Local_curr_dir = OS. getcwd ()
Files, dirs = self. get_dirs_files ()
Print "FILES:", files
Print "DIRS:", dirs
For f in files:
Print next_dir, ':', f
Outf = open (f, 'wb ')
Try:
Self. conn. retrbinary ('retr % s' % f, outf. write)
Finally:
Outf. close ()
For d in dirs:
OS. chdir (local_curr_dir)
Self. conn. cwd (ftp_curr_dir)
Self. walk (d)
Def run (self ):
Self. walk ('.')
Def main ():
F = FTPSync ()
F. run ()
If _ name _ = '_ main __':
Main ()
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.