通过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的Django中django-userena组件的简单使用教程

利用twitter/bootstrap,项目的基础模板算是顺利搞定。接下来开始处理用户中心。 用户中心主要包括用户登陆、注册以及头像等个人信息维护。此前,用户的注册管理我一直使用djan...

用Python写飞机大战游戏之pygame入门(4):获取鼠标的位置及运动

用Python写飞机大战游戏之pygame入门(4):获取鼠标的位置及运动

目标是拷贝微信的飞机大战,当然拷贝完以后大家就具备自己添加不同内容的能力了。 首先是要拿到一些图片素材,熟悉使用图像处理软件和绘画的人可以自己制作,并没有这项技能的同学只能和我一样从网上...

如何使用VSCode愉快的写Python于调试配置步骤

如何使用VSCode愉快的写Python于调试配置步骤

在学习Python的过程中,一直没有找到比较趁手的第三方编辑器,用的最多的还是Python自带的编辑器。由于本人用惯了宇宙第一IDE(Visual Studio),所以当Visual S...

Mac安装python3的方法步骤

Mac安装python3的方法步骤

Python有两个版本,一个是2.x版,一个是3.x版,这两个版本是不兼容的。 现在 Mac 上默认安装的 python 版本为 2.7 版本,若 安装 新版本需要 通过 该地址进行下载...

Django 视图层(view)的使用

视图层(view) 视图函数,简称视图,本质上是一个简单的Python函数,它接受Web请求并且返回Web响应。响应的内容可以是HTML网页,重定向,404错误,图片等任何东西,但本质...