Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Read from URL, write to file
"""
Code to write data read from a URL to a file
Based on an answer on SO:
http://stackoverflow.com/questions/22676/how-do-i-download-a-file-over-http-using-python/22721
"""
import urllib2
mp3file = urllib2.urlopen("http://www.example.com/songs/mp3.mp3")
with open('test.mp3', 'wb') as output:
while True:
data = mp3file.read(4096)
if data:
output.write(data)
else:
break
@fitoprincipe

This comment has been minimized.

Copy link

@fitoprincipe fitoprincipe commented Nov 16, 2016

Hello, I found your script useful, but have one question: can I use the file for post-processing? suppose I download a jpg file that I want to process with OpenCV, can I use the 'data' variable to keep working? or do I have to read it again from the downloaded file?

@Project-Magenta

This comment has been minimized.

Copy link

@Project-Magenta Project-Magenta commented Jan 20, 2019

data should be a block of bytes

@Project-Magenta

This comment has been minimized.

Copy link

@Project-Magenta Project-Magenta commented Jan 20, 2019

4096 to be exact

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment