【问题标题】:How to download file from ftp?如何从 ftp 下载文件?
【发布时间】:2011-10-23 19:25:35
【问题描述】:

我正在用 python 编写一个安装脚本。

如何在 python 中从 ftp 下载文件?

操作系统——Windows XP——如果有影响的话。

【问题讨论】:

    标签: python file ftp windows-xp installation


    【解决方案1】:
    from urllib.request import urlopen
    try:
        req = urlopen('ftp://ftp.expasy.org/databases/enzyme/enzclass.txt')
    except:
        print ("Error")
    

    【讨论】:

      【解决方案2】:
      from urllib2 import urlopen
      req = urlopen('ftp://ftp.gnu.org/README')
      

      然后您可以使用req.read() 将文件内容加载到变量中或对其执行任何其他操作,或者使用shutil.copyfileobj 将内容保存到磁盘而不将其加载到内存中。

      【讨论】:

        【解决方案3】:

        使用ftplib

        文档中的代码示例:

        >>> from ftplib import FTP
        >>> ftp = FTP('ftp.cwi.nl')   # connect to host, default port
        >>> ftp.login()               # user anonymous, passwd anonymous@
        >>> ftp.retrlines('LIST')     # list directory contents
        total 24418
        drwxrwsr-x   5 ftp-usr  pdmaint     1536 Mar 20 09:48 .
        dr-xr-srwt 105 ftp-usr  pdmaint     1536 Mar 21 14:32 ..
        -rw-r--r--   1 ftp-usr  pdmaint     5305 Mar 20 09:48 INDEX
         .
         .
         .
        >>> ftp.retrbinary('RETR README', open('README', 'wb').write)
        '226 Transfer complete.'
        >>> ftp.quit()
        

        【讨论】:

          【解决方案4】:

          这是我目前正在使用的代码 sn-p。

          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
          

          用法:

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

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

          由于你好像比较懒,下面是直接下载文件到本地文件的代码:

          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()
          

          如果你指定一个以斜杠结尾的路径,这个方法很聪明,可以使用服务器发送的文件名,否则它使用你指定的目标。

          【讨论】:

          • 你能给个更简单的选择吗?
          • 认真的吗?有什么比只使用复制粘贴来进行单行函数调用更容易的呢?
          • 在哪里输入文件名?
          猜你喜欢
          • 1970-01-01
          • 2014-08-05
          • 2021-10-10
          • 1970-01-01
          • 2015-05-06
          • 1970-01-01
          • 1970-01-01
          • 2018-06-22
          相关资源
          最近更新 更多