views:

55

answers:

1

Okay, so this is really messed. I've setup a script to download an mp3 using urllib2 in Python.

url = 'example.com'
req2 = urllib2.Request(url)
response = urllib2.urlopen(req2)

#grab the data
data = response.read()

mp3Name = "song.mp3"
song = open(mp3Name, "w")
song.write(data2)
song.close()

Turns out it was somehow related to me downloading it on windows or my current Python version. I tested the code on my Ubuntu distro and the mp3 file downloaded perfectly fine....

So I just used simple urllib2.openurl and it worked perfect!

Does anyone have any clue what was causing the weird issue running the code on my Windows box?

I am using a newer version of Python but I feel like it can't be that...

If it matters the mp3 are encoded in LAME

I wonder why downloading on Windows mangled the mp3?

+10  A: 

Try binary file mode. open(mp3Name, "wb") You're probably getting line ending translations.

The file is binary, yes. It's the mode that wasn't. When a file is opened, it can be set to read as a text file (this is default). When it does this, it will convert line endings to match the platform. On Windows, line ends are \r\n In most other places it's either \r or \n. This change messes up the data stream.

JoshD
dang crazy! I thought it was already binary otherwise it wouldn't sorta play. I thought it was on by default!
Setheron
@Setheron: I added a bit of detail to the answer.
JoshD