码迷,mamicode.com
首页 > 编程语言 > 详细

Python FTP 下载文件 简单示例

时间:2015-01-09 17:32:39      阅读:464      评论:0      收藏:0      [点我收藏+]

标签:ftp   download   python   

简单的FTP下载 ,不加任何异常判断。


<span style="font-size:14px;">import os

from ftplib import FTP

ftp_addr = '10.10.0.1'

f=FTP(ftp_addr)
f.login('anonymous')
f.cwd("apk_download/")    
remote_file = '20141223140651.apk'
f.retrbinary("RETR %s" % remote_file, open(remote_file, "wb").write)</span>


网上搜到个带 异常处理的版本 来自

http://www.hiadmin.org/code/python-ftp 

<span style="font-size:14px;">#! encoding:utf-8
# Filename : ftptestdown.py
#使用ftplib.error_perm函数来打印输出错误信息

import ftplib
import os
import socket

remote_host = "ftp.kernel.org"
remote_dir = "/pub/linux/kernel/v1.0"
remote_file = "patch8.gz"
def kernelmain():
    try:
        ftp = ftplib.FTP(remote_host)
    except (socket.error, socket.gaierror):
        print "ERROR cannot reach '%s'" % remote_host
        return
    print "..Connected to remote_host '%s'.." %remote_host

    try:
        ftp.login() #使用匿名账号登陆也就是anonymous
    except ftplib.error_perm:
        print "ERROR cannot login anonymously"
        ftp.quit()
        return
    print "...logged in as 'anonymously'..."

    try:
        ftp.cwd(remote_dir) #切换当前工作目录
    except ftplib.error_perm:
        print "ERROR cannot cd to '%s'" % remote_dir
        ftp.quit()
        return
    print "....Changed to '%s' folder...." % remote_dir

    try:#传一个回调函数给retrbinary() 它在每接收一个二进制数据时都会被调用
        ftp.retrbinary("RETR %s" % remote_file, open(remote_file, "wb").write)
    except ftplib.error_perm:
        print "ERROR cannot remote_file '%s'" % remote_file
        os.unlink(remote_file)
    else:
        print ".....Download '%s' to cwd....." % remote_file
    
    ftp.quit()
    return

#调用函数执行测试
if __name__ == "__main__":
    kernelmain()</span>




Python FTP 下载文件 简单示例

标签:ftp   download   python   

原文地址:http://blog.csdn.net/u012063703/article/details/42555289

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!