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

yipeiwu_com6年前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开发之str.format()用法实例分析

本文实例分析了python开发之str.format()用法。分享给大家供大家参考,具体如下: 格式化一个字符串的输出结果,我们在很多地方都可以看到,如:c/c++中都有见过 下面看看p...

python使用正则搜索字符串或文件中的浮点数代码实例

用python和numpy处理数据次数比较多,写了几个小函数,可以方便地读写数据: # -*- coding: utf-8 -*- #------------------------...

python飞机大战pygame游戏框架搭建操作详解

python飞机大战pygame游戏框架搭建操作详解

本文实例讲述了python飞机大战pygame游戏框架搭建操作。分享给大家供大家参考,具体如下: 目标 明确主程序职责 实现主程序类 准备游戏精灵组 01. 明确主程序职...

解决Python2.7中IDLE启动没有反应的问题

解决Python2.7中IDLE启动没有反应的问题

安装Python2.7后,它自带一个编辑器IDLE,但是使用几次之后出现启动不了的情况,可做如下操作。 Windows操作系统下,使用快捷键 win+R 启动“运行”对话框,输入下面的路...

pycharm新建一个python工程步骤

pycharm新建一个python工程步骤

小编最近由于工作原因要用到python,一门新的知识需要接触,对于我来说难度还是很大的。 python工程目录结构 每次创建一个python工程 PyCharm会创建如下目录 创建时会把...