如何让用python下载文件
时间: 2023-05-25 14:03:51 浏览: 54
在 Python 中,您可以使用 urllib 模块或 requests 模块中的下载文件功能来下载文件。
使用 urllib 模块下载文件的代码示例为:
```python
import urllib.request
url = 'https://example.com/image.jpg'
urllib.request.urlretrieve(url, 'image.jpg')
```
在这个例子中,我们使用 `urllib.request.urlretrieve()` 函数来下载文件并将其保存到本地文件“image.jpg”中。
使用 requests 模块下载文件的代码示例为:
```python
import requests
url = 'https://example.com/image.jpg'
r = requests.get(url)
with open('image.jpg', 'wb') as f:
f.write(r.content)
```
在这个例子中,我们发送 GET 请求以获取文件并将响应内容写入本地文件“image.jpg”中。使用 `with` 语句可以确保文件句柄被正确关闭。
无论您使用哪种方法,您也可以通过修改 URL 和文件名来下载不同类型的文件。
相关问题
如何让用python自动下载文件
可以使用Python中的urllib库来实现自动下载文件。以下是一个简单的示例代码:
```python
import urllib.request
url = 'http://example.com/file.zip'
filename = 'file.zip'
try:
urllib.request.urlretrieve(url, filename)
print('文件下载成功')
except Exception as e:
print(f'文件下载失败: {str(e)}')
```
在这个示例中,我们指定了需要下载的文件的URL和本地保存的文件名。然后,我们使用`urllib.request.urlretrieve()`函数来下载文件。如果下载成功,将输出“文件下载成功”。如果下载失败,则将输出错误消息。
如何使用Python下载文件?
以下是使用Python下载文件的两种方法:
1. 使用urllib模块下载文件:
```python
import urllib.request
url = "http://example.com/file.txt"
filename = "file.txt"
urllib.request.urlretrieve(url, filename)
```
2. 使用requests模块下载文件:
```python
import requests
url = "http://example.com/file.txt"
filename = "file.txt"
response = requests.get(url)
with open(filename, "wb") as file:
file.write(response.content)
```