Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downloading Mp3 using Python in Windows mangles the song however in Linux it doesn't

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(data)    # was 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 the simple urllib2.openurl method and it worked perfect!

To summarize:

  • I am using urllib2.openurl in Python on an Ubuntu distro.
  • I am using a newer version of Python but I feel like it can't be that.
  • The mp3 are encoded in LAME.

Does anyone have any clue what was causing the weird issue running the code on my Windows box? I wonder why downloading on Windows mangled the mp3?

like image 909
Setheron Avatar asked Oct 07 '10 05:10

Setheron


1 Answers

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.

like image 169
JoshD Avatar answered Oct 11 '22 15:10

JoshD