在Python中,你可以使用多种方法来下载文件并保存到指定的目录。以下是一个简单的示例,展示了如何使用requests
库来下载文件:
以下是一个简单的Python脚本,用于下载文件并保存到指定的目录:
import requests
import os
def download_file(url, directory):
# 确保目标目录存在
if not os.path.exists(directory):
os.makedirs(directory)
# 提取文件名
filename = url.split('/')[-1]
filepath = os.path.join(directory, filename)
try:
# 发送HTTP请求
response = requests.get(url, stream=True)
response.raise_for_status() # 如果请求失败,抛出HTTPError异常
# 写入文件
with open(filepath, 'wb') as file:
for chunk in response.iter_content(chunk_size=8192):
if chunk:
file.write(chunk)
print(f"文件已成功下载到 {filepath}")
except requests.exceptions.HTTPError as http_err:
print(f"HTTP错误发生: {http_err}")
except Exception as err:
print(f"其他错误发生: {err}")
# 使用示例
url = 'http://example.com/file.zip'
directory = '/path/to/save'
download_file(url, directory)
通过上述方法,你可以有效地在Python中下载文件并处理可能遇到的问题。
领取专属 10元无门槛券
手把手带您无忧上云