python ftp 下载

刚学习了《python核心编程》的第十七章,ftp编程,写了一个小脚本下载ftp网站上的全部文件,还没学习多线程编程,后面要给加上多线程下载。
from ftplib import FTP
import re
import os


host = 'ftp.neu.edu.cn'
dir_path = '/ebook/python'

def get_filename(string):
    patt = re.compile(r'2011\s(.+)')
    filename = re.findall(patt, string)[0]
    return filename
    

def main():
    filenames = []
    try:
        fp = FTP(host)
    except Exception:
        print "can not connect to ",host
        return 
    print 'connect to ',host,' successfully'
    try:
        fp.login()
    except Exception:
        print 'login failed'
        return 
    print 'login successfully'
    
    try:
        fp.cwd(dir_path)
    except Exception:
        print 'change to directory:',dir_path," failed"
        fp.quit()
        return
    print 'change to directory %s successfully' %(fp.pwd())
    
    fp.retrlines('LIST',lambda x:filenames.append(get_filename(x)))
    """for filename in filenames:
        print filename
    return 
    """
    for filename in filenames:
        try:
            fp.retrbinary('RETR %s' %filename, open(filename,'wb').write)
        except Exception ,e:
            print e
        print '%s download successfully' % filename
    fp.quit()
    print 'all file download successfully'

if __name__ == "__main__":
    main()
    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值