python - Downloading file from website using requests

Viewed 39

I'm trying to download mp3 files from https://www.alain-pennec.bzh/editions/livre-mp3/mp3/ with the following code :

import requests

def main():
    for i in range(0, 226) :
        URL = "https://www.alain-pennec.bzh/editions/livre-mp3/mp3/AP"+numberOn3Char(i)+".mp3"
        response = requests.get(URL)
        open("AP"+numberOn3Char(i)+".mp3", "wb").write(response.content)
        print(numberOn3Char(i)+" OK")

def numberOn3Char(i):
    ret = str(i)
    if len(ret) == 1 :
        ret = '00' + ret
    elif len(ret) == 2 :
        ret = '0' + ret
    return ret

main()

My issue is that nothing is being downloaded. I get no error and I don't understand why it's not working.

1 Answers

Try changing

open("AP"+numberOn3Char(i)+".mp3", "wb").write(response.content)

to

 name = "AP"+numberOn3Char(i)+".mp3"
 with open(name, 'wb') as f:
    f.write(response.content)

and see if it works.

Related