python下载文件到指定目录
时间: 2023-02-17 19:20:06 浏览: 55
在 Python 中可以使用 `urllib` 模块来下载文件。可以使用 `urllib.request.urlretrieve(url, filename)` 方法将文件下载到指定的目录。
```
import urllib.request
url = 'http://www.example.com/file.txt'
filename = '/path/to/save/file.txt'
urllib.request.urlretrieve(url, filename)
```
上面的代码将文件 `file.txt` 从网址 `http://www.example.com/file.txt` 下载到本地目录 `/path/to/save/` 中。
相关问题
python 下载文件到指定目录的脚本
可以使用 Python 的 `urllib` 模块来下载文件,然后使用 `os` 模块来保存到指定目录。
下面是一个示例脚本,用于从 URL 下载文件并将其保存到指定目录:
```python
import os
from urllib import request
url = "http://example.com/file.txt"
save_path = "/path/to/save/directory"
filename = url.split("/")[-1]
full_save_path = os.path.join(save_path, filename)
request.urlretrieve(url, full_save_path)
print(f"File downloaded and saved to {full_save_path}")
```
在这个示例中,我们首先定义了要下载的文件的 URL 和要保存到的目录路径。然后我们从 URL 中提取文件名,并使用 `os.path.join()` 函数来构建完整的保存路径。
最后,我们使用 `urllib.request.urlretrieve()` 函数下载文件并将其保存到指定目录。完成后,我们打印了保存文件的完整路径。
请注意,下载大型文件时可能需要更长的时间,具体取决于您的网络速度。
python下载文件到指定目录 用requests 并且判断是否下载完成
可以使用 Python 库 `requests` 下载文件到指定目录。下载文件的代码示例如下:
```python
import requests
url = 'https://www.example.com/file.zip'
r = requests.get(url, allow_redirects=True)
open('path/to/save/file.zip', 'wb').write(r.content)
```
可以通过检查 `r.status_code` 来判断下载是否成功,如果等于 200 就表示下载成功。
```python
if r.status_code == 200:
open('path/to/save/file.zip', 'wb').write(r.content)
print("下载成功")
else:
print("下载失败")
```
如果想确定文件下载完成,可以使用`r.headers.get("content-length")`来确定文件大小,并且再次进行判断.
```python
import os
size = int(r.headers.get("content-length"))
if os.path.getsize('path/to/save/file.zip') == size:
print("下载完成")
else:
print("下载未完成")
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)