通过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查找指定具有相同内容文件的方法

本文实例讲述了python查找指定具有相同内容文件的方法。分享给大家供大家参考。具体如下: python代码用于查找指定具有相同内容的文件,可以同时指定多个目录 调用方式:python...

详解Python编程中time模块的使用

一、简介 time模块提供各种操作时间的函数 说明:一般有两种表示时间的方式: 第一种是时间戳的方式(相对于1970.1.1 00:00:00以秒计算的偏移量),时间戳是惟一的 第二种以...

Python两个字典键同值相加的几种方法

两个字典A = {'a': 1, 'b': 2, 'c': 3}, B = {'b': 4, 'c': 6, 'd': 8} 要合并这两个字典,键值同则相加。 两个字典如果不考虑键相同则...

Django框架基础模板标签与filter使用方法详解

Django框架基础模板标签与filter使用方法详解

本文实例讲述了Django框架基础模板标签与filter使用方法。分享给大家供大家参考,具体如下: 一、基本的模板语言 1、变量 {{ }} 1.1、进入Django shell 环境...

Python OpenCV 直方图的计算与显示的方法示例

Python OpenCV 直方图的计算与显示的方法示例

本篇文章介绍如何用OpenCV Python来计算直方图,并简略介绍用NumPy和Matplotlib计算和绘制直方图 直方图的背景知识、用途什么的就直接略过去了。这里直接介绍方法。 计...