牌語備忘録 -pygo

あくまでもメモです。なるべくオフィシャルの情報を参照してください。

牌語備忘録 -pygo

Pythonでファイルをダウンロードしてみるメモ

(python2.7.13)

$ pip install requests

# coding=utf8
import os
import shutil

import requests


def download_file(url, file_dir):
    if not os.path.exists(file_dir):
        os.makedirs(file_dir)

    response = requests.get(url, stream=True)

    if response.status_code == 200:
        url_split_list = url.split('?')
        if 1 < len(url_split_list):
            url = url_split_list[0]

        basename = os.path.basename(url)
        file_path = os.path.join(file_dir, basename)

        with open(file_path, 'wb') as f:
            response.raw.decode_content = True
            shutil.copyfileobj(response.raw, f)
            return file_path
    else:
        raise 'Error:{}'.format(response.status_code)
    return

実行してないので動くかわからないけど一応メモ

参考リンク