Python中如何使用wget下载文件
发布时间:2023-12-13 15:42:17
在Python中,可以使用两种不同的方式下载文件。一种是使用内置的urllib模块,另一种是使用第三方库wget。
方式一:使用urllib下载文件
import urllib.request url = 'https://example.com/file.txt' save_path = '/path/to/save/file.txt' urllib.request.urlretrieve(url, save_path)
上述代码使用urlretrieve函数从指定的URL下载文件,并将其保存到save_path路径下。需要注意的是,此方法是阻塞的,即在下载过程中程序会暂停。
方式二:使用wget库下载文件
安装wget库:
pip install wget
import wget url = 'https://example.com/file.txt' save_path = '/path/to/save/file.txt' wget.download(url, save_path)
上述代码使用wget.download函数从指定的URL下载文件,并将其保存到save_path路径下。这种方式是非阻塞的,即下载过程中程序会继续执行。
使用wget库还可以获取下载进度:
import wget
url = 'https://example.com/big_file.zip'
save_path = '/path/to/save/big_file.zip'
def progress_callback(current, total):
percent = current / total * 100
print(f"Downloaded {current} of {total} bytes ({percent:.2f}%)")
wget.download(url, save_path, bar=progress_callback)
上述代码定义了一个名为progress_callback的回调函数,用于跟踪下载进度。在wget.download函数中,通过传递bar参数指定回调函数,从而实现了在下载过程中实时打印下载进度。
总结:
以上介绍了在Python中使用urllib和wget两种方式下载文件的方法,并提供了相关的代码示例。根据实际需求选择合适的方式进行文件下载操作。
