Introduction to three methods for downloading files using python

Source: Internet
Author: User
During Python development, you may need to download files. The most common method is to use urllib or urllib2 through Http. You can also use ftplib to download files from the ftp site. During Python development, you may need to download files. The most common method is to use urllib or urllib2 through Http.

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

The following describes how to download a zip file:

Method 1:

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

Method 2:

import urllib2print "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 3:

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)

It seems that using urllib is the easiest, just a statement. Of course, you can abbreviated urllib2:

F = urllib2.urlopen (url)

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

Code. write (f. read ())

The above describes how to download files using python. For more information, see other related articles in the first PHP community!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.