Likhit
Likhit

Reputation: 809

Creating a URLretreive function using urllib2 in python

I want to have a function which can save a page from the web into a designated path using urllib2.

Problem with urllib is that it doesn't check for Error 404, but unfortunately urllib2 doesn't have such a function although it can check for http errors.

How can i make a function to save the file permanently to a path?

def save(url,path):
  g=urllib2.urlopen(url)
  *do something to save g to 'path'*

Upvotes: 0

Views: 156

Answers (1)

Mark
Mark

Reputation: 108537

Just use .read() to get the contents and write it to a file path.

def save(url,path):
  g = urllib2.urlopen(url)
  with open(path, "w") as fH:
    fH.write(g.read())

Upvotes: 1

Related Questions