[Tutor] Request Module Corrupts Zip File
Alan Gauld
alan.gauld at yahoo.co.uk
Mon May 18 19:14:29 EDT 2020
On 18/05/2020 21:36, Nathan Prince wrote:
> Why does a downloaded zip file using requests end up corrupted?
> while(True):
> tim = datetime.datetime.now()
> if tim.strftime("%H:%M") == DLTime:
> print("Download Started")
> myfile = requests.get(url)
> open(Location, 'wb').write(myfile.content)
You should never do this. Although you say it only fails
with zip files it is just a matter of time before it fails
with others. When writing to a file always close the file
to force the buffers to be flushed from memory to the file.
(Or call flush() explicitly)
The Pythonic way to do this is to use with:
with open(Location, 'wb') as outfile:
outfile.write(myfile.content)
And 'with' will guarantee to close the file for you.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list