Python 3 resuma a file download

zljubisic at gmail.com zljubisic at gmail.com
Sun Jul 5 07:31:02 CEST 2015


I have a working solution. :)
The function below will download a file securely.
Thank anyone who helped. I wouldn't be able to write this function without your help.
I hope, someone else will benefit from our united work.

Best regards.

import os
import urllib.request

def Download(rfile, lfile):

    lsize = -1
    rsize = -2

    while True:
            try:
                if os.path.isfile(lfile):
                    lsize = os.stat(lfile).st_size
                else:
                    lsize = 0

                req = urllib.request.Request(rfile)

                rsize = urllib.request.urlopen(req).length

                if lsize == rsize:
                    break

                req.add_header('Range', "bytes={}-".format(lsize))

                response = urllib.request.urlopen(req)

                with open(lfile, 'ab') as out_file:
                    chunk = response.read(64 * 1024)

                    if not chunk:
                        break

                    out_file.write(chunk)
                    out_file.flush()

                    lsize = os.stat(lfile).st_size
                    prc_dloaded = round(lsize / rsize * 100, 2)

                    print(prc_dloaded)
                    if prc_dloaded == 100:
                        break
            except ConnectionResetError as e:
                print('Exception ConnectionResetError {0} %'.format(prc_dloaded))

    if lsize == rsize:
        retval = True
    else:
        retval = False

    return retval


while not Download('http://video.hrt.hr/2906/otv296.mp4', 'otv296.mp4'):
    print('1')


More information about the Python-list mailing list