Python 3 resuma a file download

Peter Otten __peter__ at web.de
Wed Jul 1 16:06:51 EDT 2015


zljubisic at gmail.com wrote:

> New version with chunks:
> 
> 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))
> 
> 
>     response = urllib.request.urlopen(req)
> 
>     with open(lfile, 'ab') as out_file:
>         while True:
>             try:
>                 chunk = response.read(8192)
>                 if not chunk: break
>                 out_file.write(chunk)
>             except ConnectionResetError as e:
>                 print('Exception ConnectionResetError
>                 {0}'.format(os.stat(lfile).st_size))

Catching the exception inside the while-True loop is not a good idea.

>     if response.headers.headers['Content-Length'] ==
>     os.stat(lfile).st_size:
>         retval = True
> 
>     return retval
> 
> Download('http://video.hrt.hr/2906/otv296.mp4',
> 'c:\\Users\\zoran\\hrt\\sync\\otv296.mp4')





More information about the Python-list mailing list