Python 3 resuma a file download

MRAB python at mrabarnett.plus.com
Thu Jul 2 18:07:39 EDT 2015


On 2015-07-02 21:27, zljubisic at gmail.com wrote:
> This is my final version which doesn't work. :(
> Actually, it works with another file on another server, but doesn't work with mp4 files on this particular server.
>
> I really don't know what to do?
>
> Regards.
>
> 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)
>
>      rfsize = urllib.request.urlopen(req).length
>
>      req.add_header('Range', "bytes={}-".format(lsize))
>
>      response = urllib.request.urlopen(req)
>
>      with open(lfile, 'ab') as out_file:
>          while True:
>              try:
>                  chunk = response.read(64 * 1024)
>                  # chunk = response.read(128)
>                  if not chunk: break
>                  out_file.write(chunk)
>                  out_file.flush()
>
>
>                  lfsize = os.stat(lfile).st_size
>
>                   print("{0:.2f}".format(lfsize / rfsize * 100))
>              except ConnectionResetError as e:
>                  print('Exception ConnectionResetError {0}'.format(os.stat(lfile).st_size))
>                  response = urllib.request.urlopen(req)
>
>
>      if lfsize == rfsize:
>          retval = True
>
>      return retval
>
>
> while not Download('http://video.hrt.hr/2906/otv296.mp4', 'otv296.mp4'):
>      print('1')
>
If a ConnectionResetError is raised, it'll restart the request from the
beginning, but continue appending to the same file. You should reset
the writing too.




More information about the Python-list mailing list