Download file

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.

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('http://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()

Class

3 thoughts on “Download file

  1. Reply
    Boycha - July 18, 2016

    While downloading the text file decode it in utf-8 or else it will give an error because the argument of file_.write needs to be string

    1. Reply
      Wilson - July 28, 2016

      I just find the solution
      file = open(“readddme.txt”,”wb”)

  2. Reply
    Khoa - August 7, 2016

    Hi, is this the end of the tutorial? Great thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *