Python下载文件实例

Downloading files from the internet is something that almost every programmer will have to do at some point.

Python provides several ways to do just that in its standard library. Probably the most popular way to download a file is over HTTP using the urllib or urllib2 module.

Python also comes with ftplib for FTP downloads.

Finally there’s a new 3rd party module that’s getting a lot of buzz called requests. We’ll be focusing on the two urllib modules and requests for this article.


Since this is a pretty simple task, we’ll just show a quick and dirty script. that downloads the same file with each library and names the result slightly differently. We will download a zipped file from this very blog for our example script. Let’s take a look:

CODE:

import urllib
import urllib2
import requests

url = 'http://www.blog.pythonlibrary.org/wp-content/uploads/2012/06/wxDbViewer.zip'

print "downloading with urllib"
urllib.urlretrieve(url, "code.zip")

print "downloading with urllib2"
f = urllib2.urlopen(url)
data = f.read()
with open("code2.zip", "wb") as code:
    code.write(data)

print "downloading with requests"
r = requests.get(url)
with open("code3.zip", "wb") as code:
    code.write(r.content)

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/301743/viewspace-732521/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/301743/viewspace-732521/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值