通过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中解析JSON并同时进行自定义编码处理实例

在对文件内容或字符串进行JSON反序列化(deserialize)时,由于原始内容编码问题,可能需要对反序列化后的内容进行编码处理(如将unicode对象转换为str)。 在Python...

Python中用Descriptor实现类级属性(Property)详解

上篇文章简单介绍了python中描述器(Descriptor)的概念和使用,有心的同学估计已经Get√了该技能。本篇文章通过一个Descriptor的使用场景再次给出一个案例,让不了解情...

python基于pyDes库实现des加密的方法

本文实例讲述了python基于pyDes库实现des加密的方法。分享给大家供大家参考,具体如下: 下载及简介地址:https://twhiteman.netfirms.com/des.h...

python监控文件或目录变化

本文实例实现的功能是监控一个文件或目录的变化,如果有变化,把文件上传备份至备份主机,并且要监控上传过程是否有问题等,具体内容如下 #!/usr/bin/env python #co...

Python中的defaultdict模块和namedtuple模块的简单入门指南

在Python中有一些内置的数据类型,比如int, str, list, tuple, dict等。Python的collections模块在这些内置数据类型的基础上,提供了几个额外的数...