在Python中使用requests和zipfile库下载和解压文件
在Python中,可以使用requests库来下载文件,使用zipfile库来解压文件。以下是使用这两个库来实现上述功能的代码:
import requests
import zipfile
# 下载文件
url = 'https://labfile.oss.aliyuncs.com/courses/2616/seaborn-data.zip'
filename = 'seaborn-data.zip'
response = requests.get(url)
with open(filename, 'wb') as file:
file.write(response.content)
# 解压文件
with zipfile.ZipFile(filename, 'r') as zip_ref:
zip_ref.extractall('~/')
以上代码使用requests.get()方法下载文件,并使用open()方法将文件内容写入本地文件。然后,使用zipfile.ZipFile()方法打开压缩文件,并使用extractall()方法将文件解压到指定目录。
原文地址: https://www.cveoy.top/t/topic/phNM 著作权归作者所有。请勿转载和采集!