Thursday, September 8, 2016

How to download an audio file in Python ? How to download an video file in Python ? How to download any file in Python ?

This example shows downloading an mp3 file by using urllib and urllib2.

# Python 3 code
import urllib.request, urllib.parse, urllib.error

url = 'http://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3'

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

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


 If you downlad a zip, file change the line
urllib.request.urlretrieve(url, "code.mp3")
with
urllib.request.urlretrieve(url, "code.zip")

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


Apply the same thing if you want to download any file format.

Reference :
http://www.blog.pythonlibrary.org/2012/06/07/python-101-how-to-download-a-file/