Python Forum

Full Version: Why the file is not downloaded in full with this script?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I use python3 and this little script next
import requests

url = 'http://mp3-red.co/stream/44760541/oscar-peterson-night-and-day.mp3'
r = requests.get (url, allow_redirects = True)
open ('oscar-peterson-night-and-day.mp3', 'wb'). write (r.content)
should allow the download of the file by giving the name of the url included in the py.
The file is downloading but not entirely!
Why?

Thank you for your help
Envoyer des commentaires
Historique
Enregistré
Communauté
Is there any .mp3 on that terrible "illegal" site that work Dodgy

Back to Python,this is how you download.
import requests

url = 'http://file-examples.com/wp-content/uploads/2017/11/file_example_MP3_700KB.mp3'
with open('sample.mp3', 'wb') as f:
    f.write(requests.get(url).content)
Get file name from url.
import requests
import os

url = 'http://file-examples.com/wp-content/uploads/2017/11/file_example_MP3_700KB.mp3'
file_name = os.path.basename(url)
with open(file_name, 'wb') as f:
    f.write(requests.get(url).content)
You should always close the file, after you're done with writing.
The context manager does it for you. After the interpreter leaves the with-block,
it closes the file. Only when the file is closed, it's guaranteed, that all buffers are written.
It is explained here: http://blog.lerner.co.il/dont-use-python...r-depends/

If you don't use a context manager, you've to close the file explicit.
fd = open(.....)
fd.write('something')
fd.close()