In [73]:
##################################################################################
# Title      : Download any file from web                                        #
# Description: The easiest way to download any file from web and save it locally #
##################################################################################

import urllib
import urllib.request
import os

class bcolors:
    '''To print in terminal with colors'''
    GREEN_BOLD = '\033[92m' + '\033[1m'
    ENDC = '\033[0m'
    
url = '''https://prasanth-ntu.github.io/html/ML-Course/Intro-to-ML-with-Python/data/ex1data1.txt'''

# extracts the file name from the given url (change the file_name to suit your needs)
file_name =  url.split("/")[-1]
print ("File name extracted from URL: "+ bcolors.GREEN_BOLD + file_name + bcolors.ENDC)

# uncomment the line below to print the current working directory
#print ("Current working dir:", os.getcwd())   

if not os.path.exists(file_name):
    # file will be downloaded from web and stored in current directoy 
    file_name_out, message = urllib.request.urlretrieve(url = url, filename = file_name)   
    print ("File downloaded to:", file_name_out, "in current working directoy")
else:
    # skip downloading if the file already exists in the current directory
    print ("File already exists:", file_name, "in current working directoy")
File name extracted from URL: ex1data1.txt
File downloaded to: ex1data1.txt in current working directoy
In [80]:
url = "http://www.py4inf.com/code/words.py"

file_name =  url.split("/")[-1]
print ("File name extracted from URL: "+ bcolors.GREEN_BOLD + file_name + bcolors.ENDC)

file_name_out, message = urllib.request.urlretrieve(url = url, filename = file_name)   
print ("File downloaded to:", file_name_out, "in current working directoy")
File name extracted from URL: words.py
File downloaded to: words.py in current working directoy