1. 程式人生 > >Python使用urllib下載檔案以及使用zipfile解壓檔案

Python使用urllib下載檔案以及使用zipfile解壓檔案

首先定義檔案下載路徑,檔名

import os
from six.moves import urllib
import zipfile
DATA_URL = 'https://archive.ics.uci.edu/ml/machine-learning-databases/00240/UCI%20HAR%20Dataset.zip'
DATA_DIR = './dataset/'
DATA_NAME = 'UCI HAR Dataset.zip'

filename = DATA_NAME
filepath = os.path.join(DATA_DIR, filename)

下載檔案:

filepath, _ = urllib.request.urlretrieve(DATA_URL, filepath)

解壓檔案:

with zipfile.ZipFile(filepath, 'r') as zip:
    zip.extractall(DATA_DIR)