使用Python Requests模块无法下载文件,提示权限拒绝错误
问题解决:Python Requests下载文件触发PermissionError
核心原因
你的代码里destination变量指向的是文件夹路径(C:\Users\something\Downloads),但open()函数需要传入具体的文件路径(包含完整文件名)。尝试直接对文件夹执行写入操作,哪怕有管理员权限也会触发权限拒绝错误。
修正后的代码
import requests url = "https://github.com/something/something/releases/download/1.0/something.exe" # 补充文件名,确保destination是完整的文件路径 destination = r"C:\Users\something\Downloads\something.exe" response = requests.get(url) if response.status_code == 200: with open(destination, 'wb') as file: file.write(response.content) print("文件下载完成") else: print(f"下载失败,HTTP状态码: {response.status_code}")
额外优化建议
- 用
os.path.join拼接路径,避免手动输入路径时出错:import os folder_path = r"C:\Users\something\Downloads" file_name = "something.exe" destination = os.path.join(folder_path, file_name) - 下载大文件时,改用流式写入减少内存占用:
if response.status_code == 200: with open(destination, 'wb') as file: for chunk in response.iter_content(chunk_size=1024): file.write(chunk)
内容的提问来源于stack exchange,提问作者aki
相关产品推荐
相关产品推荐

