Categories 新闻动态

Python免费学

import os
import requests

# 定义要下载的资源ID
resource_id = '12345678'

# 尝试创建保存资源的目录
try:
    os.mkdir('资源下载')
except FileExistsError:
    pass

# 获取当前工作目录
current_dir = os.getcwd()
file_path = current_dir + '/资源下载'  # 设置保存资源文件的路径
print(file_path)  # 输出文件路径,供调试查看

url_base="https://example.com/download/"
resource_url=url_base+str(resource_id)+".zip"  # 拼接完整的URL地址

# 发送HTTP请求获取资源内容
response = requests.get(resource_url)
if response.status_code == 200:
    zip_file_content = response.content

# 验证并提取文件名
file_name = resource_id + ".zip"
file_path_with_name = file_path + '/' + file_name

# 将资源保存到本地
with open(file_path_with_name, 'wb') as f:
    f.write(zip_file_content)

# 打印提示信息
print(resource_url+'文件名:'+file_name)
print(file_name+'\n下载完成\n我们已经在当前目录创建了文件夹,'+file_name+'已成功下载!')