在Python中,使用HTTP协议进行文件上传和下载是非常常见的操作,通常我们会使用像requests这样的第三方库来简化这些操作。下面,我将分别介绍如何使用requests库来进行文件的上传和下载。
文件下载
使用requests库下载文件非常直观和简单。你可以使用get方法发送HTTP GET请求,并通过response.content或response.save()来获取或保存文件内容。
python复制代码
import requests | |
def download_file(url, save_path): | |
response = requests.get(url, stream=True) # stream=True 允许我们分块读取内容 | |
if response.status_code == 200: | |
with open(save_path, 'wb') as f: | |
for chunk in response.iter_content(chunk_size=8192): # 设置分块大小 | |
if chunk: | |
f.write(chunk) | |
print(f"File downloaded successfully to {save_path}") | |
else: | |
print(f"Failed to download file. Status code: {response.status_code}") | |
# 使用示例 | |
download_file('http://example.com/path/to/file.zip', 'downloaded_file.zip') |
总之,使用requests库可以非常方便地在Python中进行文件的上传和下载。