通过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实现猜数字游戏

python实现猜数字游戏

说明: 本例改编自《Python编程快速上手》。例子很简单我就不多说了 直接上代码,给初学python练手用。 给你6次机会猜对一个预先生成好的1-20之间的整数。覆盖一下知识点:...

解决Pycharm下面出现No R interpreter defined的问题

解决Pycharm下面出现No R interpreter defined的问题

安装Pycharm进行Python开发时,经常右下角提示No R interpreter defined,处理方式: 1、安装R,然后将R的路径添加到Pycharm中: 2、如果不需要...

python中使用psutil查看内存占用的情况

有的时候需要对python程序内存占用进行监控,这个时候可以用到psutil库,Anaconda中是自带的,如果import出错,可以用pip install psutil(安装在pyt...

Python中logging.NullHandler 的使用教程

在使用 peewee 框架时,默认是不会出现日志消息的。 from peewee import Model, CharField, DateTimeField, IntegerFie...

Python 合并多个TXT文件并统计词频的实现

Python 合并多个TXT文件并统计词频的实现

需求是:针对三篇英文文章进行分析,计算出现次数最多的 10 个单词 逻辑很清晰简单,不算难, 使用 python 读取多个 txt 文件,将文件的内容写入新的 txt 中,然后对新 tx...