Home >Backend Development >Python Tutorial >Three ways to download files in python

Three ways to download files in python

高洛峰
高洛峰Original
2016-10-19 11:53:511730browse

When you encounter the situation of downloading files during Python development, the most common method is to use the urllib or urllib2 module through Http.

Of course you can also use ftplib to download files from ftp sites. In addition, Python also provides another method, requests.

Let’s take a look at three methods to download zip files:

Method one:

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

Method two:

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

Method three:

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

Look It is easiest to use urllib, just one statement. Of course you can abbreviate urllib2 as:

f = urllib2.urlopen(url)

with open("demo2.zip", "wb") as code:

code.write(f.read())



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn