通过python下载FTP上的文件夹的实现代码

yipeiwu_com5年前Python基础
复制代码 代码如下:

# -*- 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('/')        # 远端FTP目录
        os.chdir('/data/')        # 本地下载目录
    def get_dirs_files(self):
        u''' 得到当前目录和文件, 放入dir_res列表 '''
        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)
        except 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()

相关文章

python检查字符串是否是正确ISBN的方法

本文实例讲述了python检查字符串是否是正确ISBN的方法。分享给大家供大家参考。具体实现方法如下: def isISBN(isbn): """Checks if the p...

对Python subprocess.Popen子进程管道阻塞详解

问题产生描述 使用子进程处理一个大的日志文件,并对文件进行分析查询,需要等待子进程执行的输出结果,进行下一步处理。 出问题的代码 # 启用子进程执行外部shell命令 def __s...

Python使用装饰器模拟用户登陆验证功能示例

Python使用装饰器模拟用户登陆验证功能示例

本文实例讲述了Python使用装饰器模拟用户登陆验证功能。分享给大家供大家参考,具体如下: # -*- coding:utf-8 -*- #!python3 user_list =...

Python中six模块基础用法

背景 大家知道现在python主要有两个大的版本,一个是python2另一个是python3,那么不同的人可能会习惯不同的版本,而python2和python3又有一些区别和不兼容的地...

TensorFlow Session会话控制&Variable变量详解

TensorFlow Session会话控制&Variable变量详解

这篇文章主要讲TensorFlow中的Session的用法以及Variable。 Session会话控制 Session是TensorFlow为了控制和输出文件的执行语句,运行sessi...