-1

I would like to download binary data (a .wav file) from a website using python 3.

I was able to get the binary data as a string using requests.get but when I tried to write it to a file, the data was changed and the saved file was not correct:

import requets
waveurl = 'http://www ..... /song.wav'
res = requests.get(waveurl)
with open("song.wav, "wb") as f:
    f.write(bytes(res.text)

I also tried using struct.pack("B",each_byte) but it didn't help.

How can I convert properly download and save binary data to a file without changing it?

divibisan
  • 11,659
  • 11
  • 40
  • 58
yzahavi
  • 45
  • 2
  • https://stackoverflow.com/q/25341714/1531971 –  May 30 '18 at 15:53
  • Possible duplicate of [Best way to convert string to bytes in Python 3?](https://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3) – divibisan May 30 '18 at 21:11

1 Answers1

0

Based on the Request documentation you can access the response body as bytes using content instead of text. I would recommend that you give that a try.

import request
waveurl = 'http://www ..... /song.wav'
res = requests.get(waveurl)
with open("song.wav, "wb") as f:
    f.write(res.content)

I haven't tested this option, this i meant to provide a starting point for you.

joe.liedtke
  • 582
  • 2
  • 14
  • thx it solved it yeeey Thx.... but .... still how to take string and chage his meaning as bytes without changes – yzahavi May 30 '18 at 15:52
  • In your case I would recommend getting the raw bytes, since converting a string to bytes would require you to know the char set. Here is another thread that may be helpful https://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3. And since it is a related topic you may also want to look into character sets since that is an important part of converting text to bytes https://www.joelonsoftware.com/2003/10/08/the-absolute-minimum-every-software-developer-absolutely-positively-must-know-about-unicode-and-character-sets-no-excuses/ – joe.liedtke May 30 '18 at 15:59
  • 1
    Also, since this solved your question please do consider accepting the answer. – joe.liedtke May 31 '18 at 16:38