How to download files with Python?

Recently when I tried to upgrade my Linux system, I encountered system libraries dependency issue, as a result wget, curl, scp and telnet are all not usable. How could I upload the library files to the system to fix the issue?

Luckily Python works well. I can easy download a file in command-line and save it into right place. Here it is,

# python
Python 2.4.3 (#1, Oct 23 2012, 22:02:41)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-54)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import urllib
>>> urllib.urlretrieve("http://www.admon.org/tmp/libaudit.so.0.0.0", "/lib64/libaudit.so.0.0.0")
('/lib64/libaudit.so.0.0.0', <httplib.HTTPMessage instance at 0x2ad6e9641560>)
>>> quit()
'Use Ctrl-D (i.e. EOF) to exit.'

There are two more ways for downloading files with Python,
Example: Downloading with urllib2

import urllib2
f = urllib2.urlopen(url)
data = f.read()
with open("/path/to/file.zip", "wb") as code:
    code.write(data)

Example: Downloading with requests

import requests
r = requests.get(url)
with open("/path/to/file.zip", "wb") as code:
    code.write(r.content)

Have fun.

Share Button

Leave a comment

Your email address will not be published. Required fields are marked *