简体   繁体   English

如何在 Python 中下载 zip 文件?

[英]How to download a zip file in Python?

I have a following problem.我有以下问题。 I want to download a zip file.我想下载一个 zip 文件。 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". zip 文件似乎已下载,但我无法打开它,因为“格式未知或已损坏”。 But when I put my url into Chrome and try it manually I am able to open the zip file in WinRAR.但是,当我将 url 放入 Chrome 并手动尝试时,我可以在 WinRAR 中打开 zip 文件。 Can you help me, please?你能帮我吗?

Your problem is that you are writing the contents of a zip file (which are binary) as a string.您的问题是您正在将 zip 文件(二进制)的内容作为字符串编写。 Check out this stackoverflow answer how to write a binary file you received with requests.get()查看这个 stackoverflow 答案如何编写您使用requests.get()收到的二进制文件

If you just want to download file with url and save to a specific location, use urlretrieve would be better:如果您只想下载带有 url 的文件并保存到特定位置,使用urlretrieve会更好:

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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM