Python 下载文件
时间: 2024-06-14 18:02:25 浏览: 20
在 Python 中,下载文件通常使用 `requests` 库或内置的 `urllib` 模块,它们都提供了简单易用的接口。这里是一个基本的例子:
```python
import requests
# 定义要下载的 URL 和目标文件名
url = "https://example.com/file.zip"
filename = "file.zip"
# 使用 requests 库下载文件
response = requests.get(url, stream=True)
with open(filename, 'wb') as f:
for chunk in response.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
# 使用 urllib 下载文件(稍微复杂一些)
import urllib.request
url = "http://example.com/file.txt"
with urllib.request.urlopen(url) as response, open(filename, 'wb') as f:
f.write(response.read())
相关问题
python下载文件
在Python中,有几种常用的方法可以用来下载文件。其中,使用urllib2库的方法是一种常见的方式。这个方法可以通过以下代码实现文件下载:
import urllib2
url = 'http://www.pythontab.com/test/demo.zip'
response = urllib2.urlopen(url)
data = response.read()
with open("demo2.zip", "wb") as code:
code.write(data)
另外,还可以使用urllib库的urlretrieve函数来下载文件。这个方法可以通过以下代码实现文件下载:
import urllib
url = 'http://www.pythontab.com/test/demo.zip'
urllib.urlretrieve(url, "demo.zip")
以上就是通过Python下载文件的两种常用方法。你可以根据自己的需要选择其中一种方法来实现文件下载。
Python下载文件函数代码
以下是Python下载文件的函数代码示例:
```python
import requests
def download_file(url, file_path):
r = requests.get(url)
with open(file_path, 'wb') as f:
f.write(r.content)
```
你可以将下载文件的 URL 和文件保存在本地的路径作为参数传递给此函数。