How to download a file using Python?

Couple of weeks ago, I had to write a spider that harvest data from a website into a csv file and download the images. First I was thinking how to do the download... then I came up with a simple idea and wrote a function save_image that takes the url of the jpg image and filename, downloads the file and saves it with the name given in filename.

import urllib2

def save_image(url, filename):
    usock = urllib2.urlopen(url)
    data = usock.read()
    usock.close()
    fp = open(filename, 'wb')
    fp.write(data)
    fp.close()


Actually I just write the file in binary mode. Now post your code that performs this task is a different manner.

Comments

Ivan said…


import urllib

urllib.urlretrieve("http://www.djangotutsme.com/media/media/programmers.jpg", "/path-to-your-directory/image.jpg")

Popular posts from this blog

Strip HTML tags using Python

lambda magic to find prime numbers

Convert text to ASCII and ASCII to text - Python code