yoa*_*ram 147
据我所知,正确的方法是:
import requests, zipfile, StringIO
r = requests.get(zip_file_url, stream=True)
z = zipfile.ZipFile(StringIO.StringIO(r.content))
z.extractall()
Run Code Online (Sandbox Code Playgroud)
当然你想要检查GET是否成功r.ok.
对于python 3+,将StringIO模块与io模块一起使用并使用BytesIO而不是StringIO:以下是提及此更改的发行说明.
import requests, zipfile, io
r = requests.get(zip_file_url)
z = zipfile.ZipFile(io.BytesIO(r.content))
z.extractall()
Run Code Online (Sandbox Code Playgroud)
将 .zip 文件保存到磁盘上某个位置的超轻量级解决方案(使用 Python 3.9):
import requests
url = r'https://linktofile'
output = r'C:\pathtofolder\downloaded_file.zip'
r = requests.get(url)
with open(output, 'wb') as f:
f.write(r.content)
Run Code Online (Sandbox Code Playgroud)
在这篇博客文章的帮助下,我已经使它可以与Just requests。奇怪stream的是,这样我们就无需调用content大型请求,而这将需要立即处理所有请求,从而阻塞内存。在stream通过一次通过数据一个块迭代避免这一点。
url = 'https://www2.census.gov/geo/tiger/GENZ2017/shp/cb_2017_02_tract_500k.zip'
target_path = 'alaska.zip'
response = requests.get(url, stream=True)
handle = open(target_path, "wb")
for chunk in response.iter_content(chunk_size=512):
if chunk: # filter out keep-alive new chunks
handle.write(chunk)
handle.close()
Run Code Online (Sandbox Code Playgroud)
要么使用 urllib2.urlopen,要么你可以尝试使用优秀的Requests模块并避免 urllib2 头痛:
import requests
results = requests.get('url')
#pass results.content onto secondary processing...
Run Code Online (Sandbox Code Playgroud)
这是我在Python 3中必须要做的工作:
import zipfile, urllib.request, shutil
url = 'http://www....myzipfile.zip'
file_name = 'myzip.zip'
with urllib.request.urlopen(url) as response, open(file_name, 'wb') as out_file:
shutil.copyfileobj(response, out_file)
with zipfile.ZipFile(file_name) as zf:
zf.extractall()
Run Code Online (Sandbox Code Playgroud)
我来这里是为了寻找如何保存 .bzip2 文件。让我为可能来找这个的其他人粘贴代码。
url = "http://api.mywebsite.com"
filename = "swateek.tar.gz"
response = requests.get(url, headers=headers, auth=('myusername', 'mypassword'), timeout=50)
if response.status_code == 200:
with open(filename, 'wb') as f:
f.write(response.content)
Run Code Online (Sandbox Code Playgroud)
我只是想按原样保存文件。