python implements three methods for downloading files

  • 2020-05-24 05:48:42
  • OfStack

During the development of Python, the most common way to download files is to use urllib or urllib2 module through Http.

You can also use ftplib to download files from the ftp site. In addition, Python also provides another method, requests.

Here are three ways to download the zip file:

Method 1:


import urllib 
import urllib2 
import requests
print "downloading with urllib" 
url = 'https://www.ofstack.com//test/demo.zip' 
print "downloading with urllib"
urllib.urlretrieve(url, "demo.zip")

Method 2:


import urllib2
print "downloading with urllib2"
url = 'https://www.ofstack.com//test/demo.zip' 
f = urllib2.urlopen(url) 
data = f.read() 
with open("demo2.zip", "wb") as code:   
  code.write(data)

Method 3:


import requests 
print "downloading with requests"
url = 'https://www.ofstack.com/test/demo.zip' 
r = requests.get(url) 
with open("demo3.zip", "wb") as code:
   code.write(r.content)

It seems that urllib is the easiest to use, just one sentence. Of course you can abbreviate urllib2 to:


f = urllib2.urlopen(url) 
with open("demo2.zip", "wb") as code:
  code.write(f.read()) 

Related articles: