Python 3 resuma a file download

zljubisic at gmail.com zljubisic at gmail.com
Wed Jul 1 21:24:46 CEST 2015


Currently I am executing the following code:

import os
import urllib.request

def Download(rfile, lfile):

    retval = False

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

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


    with urllib.request.urlopen(req) as response, open(lfile, 'ab') as out_file:
        data = response.read() # a `bytes` object
        out_file.write(data)

    if response.headers.headers['Content-Length'] == os.stat(lfile).st_size:
        retval = True

    return retval

Download('http://video.hrt.hr/2906/otv296.mp4', 'otv296.mp4')

The internet connection here is very slow so execution will last for say an hour.

In meantime, can I upgrade the procedure in a way to write to file chunk by chunk instead of the whole file?

Furthermore, how to know whether the file is fully completed or not?
I trid with "if response.headers.headers['Content-Length'] == os.stat(lfile).st_size:", but I believe there is a better way.

Big regards.


More information about the Python-list mailing list