Three ways to download files in python_python

不言
Release: 2018-04-02 17:21:17
Original
5924 people have browsed it

This article mainly introduces three methods of downloading files in python. The most common method is to use urllib or urllib2 module and requests through Http. Those who are interested can learn more.

Whenever 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 the ftp site. In addition, Python also provides another method, requests.

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

Method 1:

import urllib 
import urllib2 
import requests
print "downloading with urllib" 
url = 'http://www.jb51.net//test/demo.zip' 
print "downloading with urllib"
urllib.urlretrieve(url, "demo.zip")
Copy after login

Method 2:

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

Method three:

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

It seems that using urllib is the easiest, 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())
Copy after login

Related recommendations:

Merge of Python file operations Introduction to text file content methods

The above is the detailed content of Three ways to download files in python_python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!