-
Notifications
You must be signed in to change notification settings - Fork 26
/
tar_download.py
36 lines (30 loc) · 1.04 KB
/
tar_download.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import os
import sys
import tarfile
try:
from urllib import urlretrieve
except ImportError:
from urllib.request import urlretrieve
def file_name_from_url(url, directory=None):
file_name = url.split('/')[-1]
if directory:
file_name = os.path.join(directory, file_name)
return file_name
def download_tar(url, directory=None):
if not os.path.exists(directory):
os.makedirs(directory)
file_name = file_name_from_url(url, directory)
print("Downloading {} to {}".format(url, file_name))
sys.stdout.flush()
urlretrieve(url, file_name)
def extract_contents(file_name, destination='.'):
if not os.path.exists(destination):
os.makedirs(destination)
print("Extracting {} to {}".format(file_name, destination))
sys.stdout.flush()
tar = tarfile.open(file_name)
tar.extractall(destination)
tar.close()
def download_and_extract(url, directory=None):
download_tar(url, directory)
extract_contents(file_name_from_url(url, directory), directory)