通过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中的Turtle函数库

python对函数库的引用方式 1、import <库名> 例如:import turtle 如果需要使用库函数中的函数,需要使用:<库名>.<函数名&...

Django跨域请求问题的解决方法示例

前言 本文主要给大家介绍了关于Django跨域请求问题解决的几种方法,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。 几种方法: 使用django-cors-he...

Python中Subprocess的不同函数解析

以前我一直用os.system()处理一些系统管理任务,因为我认为那是运行linux命令最简单的方式. 我们能从Python官方文档里读到应该用subprocess 模块来运行系统命令....

python 动态获取当前运行的类名和函数名的方法

一、使用内置方法和修饰器方法获取类名、函数名 python中获取函数名的情况分为内部、外部,从外部的情况好获取,使用指向函数的对象,然后用__name__属性复制代码 代码如下:def...

numpy.delete删除一列或多列的方法

基础介绍: numpy.delete numpy.delete(arr, obj, axis=None)[source] Return a new array with sub-a...