通过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 实现检验33品种数据是否是正态分布

我就废话不多说了,直接上代码吧! # -*- coding: utf-8 -*- """ Created on Thu Jun 22 17:03:16 2017 @author: y...

opencv导入头文件时报错#include的解决方法

opencv导入头文件时报错#include的解决方法

一、首先要确保你的电脑上opencv的环境和visual studio上的环境都配置好了,测试的时候通过了没有问题。 二、那么只要在你项目里面的属性设置里面配置一下包含目录就OK了,具体...

python网络编程学习笔记(六):Web客户端访问

6.1 最简单的爬虫 网络爬虫是一个自动提取网页的程序,它为搜索引擎从万维网上下载网页,是搜索引擎的重要组成。python的urllib\urllib2等模块很容易实现这一功能,下面的例...

详谈Pandas中iloc和loc以及ix的区别

Pandas库中有iloc和loc以及ix可以用来索引数据,抽取数据。但是方法一多也容易造成混淆。下面将一一来结合代码说清其中的区别。 1. iloc和loc的区别: iloc主要使用数...

Python实现的在特定目录下导入模块功能分析

本文实例讲述了Python实现的在特定目录下导入模块功能。分享给大家供大家参考,具体如下: 方法1、在指定的目录下导入特定模块,(tab.py换行自动补齐语法模块) root@kal...