python 使用requests库 下载github文件
时间: 2023-06-18 22:03:43 浏览: 69
可以使用 requests 库中的 `get()` 方法来下载 GitHub 上的文件,具体步骤如下:
1. 导入 requests 库
```python
import requests
```
2. 设置下载文件的 URL
```python
url = 'https://raw.githubusercontent.com/username/repo/branch/path/to/file'
```
其中,`username` 是 GitHub 用户名,`repo` 是仓库名,`branch` 是分支名,`path/to/file` 是文件路径。
3. 发送 GET 请求并保存文件
```python
response = requests.get(url)
with open('file_name.extension', 'wb') as f:
f.write(response.content)
```
其中,`file_name.extension` 是要保存文件的名称和扩展名,`wb` 表示二进制写入模式。
完整代码示例:
```python
import requests
url = 'https://raw.githubusercontent.com/username/repo/branch/path/to/file'
response = requests.get(url)
with open('file_name.extension', 'wb') as f:
f.write(response.content)
```
注意,若需要下载的文件需要身份验证或需要使用 access token,需要在请求头中添加相应的信息。