Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / Python FTP 下载文件 简单示例

简单的FTP下载 ,不加任何异常判断。import osfrom ftplib import FTPftp_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)还有个带 异常处理的版本#! encoding:utf-8
# Filename : ftptestdown.py
#使用ftplib.error_perm函数来打印输出错误信息import ftplib
import os
import socketremote_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()--------------------------------------分割线 --------------------------------------CentOS上源码安装Python3.4  http://www.linuxidc.com/Linux/2015-01/111870.htm《Python核心编程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm《Python开发技术详解》.( 周伟,宗杰).[高清PDF扫描版+随书视频+代码] http://www.linuxidc.com/Linux/2013-11/92693.htmPython脚本获取Linux系统信息 http://www.linuxidc.com/Linux/2013-08/88531.htm在Ubuntu下用Python搭建桌面算法交易研究环境 http://www.linuxidc.com/Linux/2013-11/92534.htmPython 语言的发展简史 http://www.linuxidc.com/Linux/2014-09/107206.htmPython 的详细介绍:请点这里
Python 的下载地址:请点这里本文永久更新链接地址:http://www.linuxidc.com/Linux/2015-02/112782.htm