bagr surfff
bagr surfff

Reputation: 5

How to download a zip file in Python?

I have a following problem. I want to download a zip file. See a following code:

import os
import requests
import time


url = "https://kriminalita.policie.cz/api/v1/downloads/202011.csv.zip"
name = url.split("/")[-1]

response = requests.get(url)

with open(os.path.join(r'C:\Users\misak\Desktop\LD_save\stazene', name), 'w') as f:
    f.write(str(response.content))

The zip file seems to be downloaded, however I am not able to open it, because "is either in unknown format or damaged". But when I put my url into Chrome and try it manually I am able to open the zip file in WinRAR. Can you help me, please?

Upvotes: 0

Views: 744

Answers (2)

mtdot
mtdot

Reputation: 312

If you just want to download file with url and save to a specific location, use urlretrieve would be better:

import urllib.request

print('Beginning file download with urllib2...')

url = 'http://i3.ytimg.com/vi/J---aiyznGQ/mqdefault.jpg'
urllib.request.urlretrieve(url, '/Users/scott/Downloads/cat.jpg')

Upvotes: 0

Taxel
Taxel

Reputation: 4207

Your problem is that you are writing the contents of a zip file (which are binary) as a string. Check out this stackoverflow answer how to write a binary file you received with requests.get()

Upvotes: 1

Related Questions