通过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()

相关文章

关于python3中setup.py小概念解析

关于 python setup.py bdist python setup.py sdist 两者的区别 sdist 指的是source dist 即源码发布,带s...

python+django+rest框架配置创建方法

python+django+rest框架配置创建方法

安装好所需要的插件和包: python、django、pip等版本如下: 采用Django REST框架3.0 1、在python文件夹下D:\python\Lib\site-pack...

Python实现的数据结构与算法之基本搜索详解

Python实现的数据结构与算法之基本搜索详解

本文实例讲述了Python实现的数据结构与算法之基本搜索。分享给大家供大家参考。具体分析如下: 一、顺序搜索 顺序搜索 是最简单直观的搜索方法:从列表开头到末尾,逐个比较待搜索项与列表中...

通过pykafka接收Kafka消息队列的方法

没有Kafka环境,所以也没有进行验证。感觉今后应该能用到,所以借抄在此,备查。 pykafka使用示例,自动消费最新消息,不重复消费: # -* coding:utf8 *- fr...

对python csv模块配置分隔符和引用符详解

如下所示: file = open('./abc.csv') csv.reader(file, delimiter=',', quotechar='"') 说明:delimiter...