如何从FTP下载文件? [英] How to download file from ftp?

查看:168
本文介绍了如何从FTP下载文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



如何从python下载ftp文件?



操作系统 - Windows XP - 如果有区别的话。

解决方案

这是我目前使用的代码片段
$ b

  import mimetypes 
import os
import urllib2
import urlparse

def filename_from_url(url):
返回os.path.basename(urlparse.urlsplit(url)[2])

def download_file(url):
创建一个urllib2请求并返回请求加上一些有用的信息
name = filename_from_url(url)
r = urllib2.urlopen(urllib2.Request(url))
info = r。 info()
如果信息中的Content-Disposition:
#如果响应具有Content-Disposition,我们从它取文件名
name = info ['Content-Disposition'] .split ('filename =')[1]
if name [0] ==''or name [0] ==':
name = name [1:-1]
elif r.geturl()!= url:
#如果我们被重定向了,从最后一个网址取文件名
name = filename_from_url(r。 geturl())
content_type = None
如果信息中的'Content-Type':
content_type = info ['Content-Type']。split(';')[0]
#尝试猜测丢失的信息
如果不是名称而不是content_type:
name ='unknown'
elif不是名称:
name ='unknown'+ mimetypes.guess_extension content_type)或''
elif not content_type:
content_type = mimetypes.guess_type(name)[0]
return r,name,content_type

用法:

  req,filename,content_type = download_file然后你可以使用 req 作为文件类对象,例如使用  shutil.copyfileobj() 将文件内容复制到本地文件中。如果MIME类型无关紧要,只需删除那部分代码即可。



由于您似乎懒惰,因此代码直接将文件下载到本地文件: / p>

 导入shutil 
def download_file_locally(url,dest):
req,filename,content_type = download_file )
如果dest.endswith('/'):
dest = os.path.join(dest,filename)
打开(dest,'wb')为f:
shutil.copyfileobj(req,f)
req.close()

如果您指定以斜杠结尾的路径,则足够聪明地使用由服务器发送的文件名,否则使用您指定的目的地。


I'm scripting an install script in python.

How do I download file from ftp in python?

Operating system -- Windows XP - if that makes a difference.

解决方案

Here's a code snippet I'm currently using.

import mimetypes
import os
import urllib2
import urlparse

def filename_from_url(url):
    return os.path.basename(urlparse.urlsplit(url)[2])

def download_file(url):
    """Create an urllib2 request and return the request plus some useful info"""
    name = filename_from_url(url)
    r = urllib2.urlopen(urllib2.Request(url))
    info = r.info()
    if 'Content-Disposition' in info:
        # If the response has Content-Disposition, we take filename from it
        name = info['Content-Disposition'].split('filename=')[1]
        if name[0] == '"' or name[0] == "'":
            name = name[1:-1]
    elif r.geturl() != url:
        # if we were redirected, take the filename from the final url
        name = filename_from_url(r.geturl())
    content_type = None
    if 'Content-Type' in info:
        content_type = info['Content-Type'].split(';')[0]
    # Try to guess missing info
    if not name and not content_type:
        name = 'unknown'
    elif not name:
        name = 'unknown' + mimetypes.guess_extension(content_type) or ''
    elif not content_type:
        content_type = mimetypes.guess_type(name)[0]
    return r, name, content_type

Usage:

req, filename, content_type = download_file('http://some.url')

Then you can use req as a file-like object and e.g. use shutil.copyfileobj() to copy the file contents into a local file. If the MIME type doesn't matter simply remove that part of the code.

Since you seem to be lazy, here's code downloading the file directly to a local file:

import shutil
def download_file_locally(url, dest):
    req, filename, content_type = download_file(url)        
    if dest.endswith('/'):
        dest = os.path.join(dest, filename)
    with open(dest, 'wb') as f:
        shutil.copyfileobj(req, f)
    req.close()

This method is smart enough to use the filename sent by the server if you specify a path ending with a slash, otherwise it uses the destination you specified.

这篇关于如何从FTP下载文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆