We can download data using the urllib2 module.. These examples work with both http, https and for any type of files including text and image.

Data will be saved in the same directory as your program resides. This means if you run your program from C:\apps\, images will be saved there too unless you explicitly specify another directory.

Related Course: Complete Python Programming Course & Exercises

Download data to variable
To download data to a variable, you can use this code:

  
import urllib2
response = urllib2.urlopen('https://wordpress.org/plugins/about/readme.txt')
data = response.read()
print(data)

The first line, ‘import urllib2’, loads the module. The second line opens the connection to the url. The method response.read() downloads data from the url and stores it into the variable data.

Download text file
To download a file you can use this code:

  
import urllib2
response = urllib2.urlopen('https://wordpress.org/plugins/about/readme.txt')
data = response.read()
filename = "readme.txt"
file_ = open(filename, 'w')
file_.write(data)
file_.close()

Download image file
Downloading an image from the web works in the same way:

  
import urllib2
response = urllib2.urlopen('https://upload.wikimedia.org/wikipedia/commons/thumb/f/f8/Python_logo_and_wordmark.svg/260px-Python_logo_and_wordmark.svg.png')
data = response.read()
filename = "image.png"
file_ = open(filename, 'w')
file_.write(data)
file_.close()

Download network examples