2011-08-10 31 views

答えて

3

ここに私が現在使っているコードスニペットがあります。

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

あなたがで終わるパスを指定する場合、このメソッドは、サーバーから送信されたファイル名を使用するのに十分スマートですスラッシュでなければ、指定した宛先が使用されます。

+0

もっと簡単なオプションはありますか? – Zygimantas

+0

真剣に?単一行の関数呼び出しを行うためにコピー&ペーストを使うより簡単ですか? – ThiefMaster

+0

ファイル名はどこに入力しますか? – Zygimantas

1

使用ftplib

ドキュメントからコードサンプル:

>>> from ftplib import FTP 
>>> ftp = FTP('ftp.cwi.nl') # connect to host, default port 
>>> ftp.login()    # user anonymous, passwd [email protected] 
>>> 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() 
6
from urllib2 import urlopen 
req = urlopen('ftp://ftp.gnu.org/README') 

その後、保存する変数にファイルの内容をロードしたり、それを他に何もするreq.read()を使用するか、またはshutil.copyfileobjすることができますそのコンテンツをメモリにロードせずにディスクに保存します。

+0

+1。短くて、甘く、働きます。 – noiv

0
from urllib.request import urlopen 
try: 
    req = urlopen('ftp://ftp.expasy.org/databases/enzyme/enzclass.txt') 
except: 
    print ("Error") 
関連する問題