欢迎访问宙启技术站
智能推送

SimpleProgress()函数实现Python文件上传/下载的进度显示

发布时间:2024-01-18 16:30:35

为了实现文件上传或下载的进度显示,可以使用tqdm库。tqdm是一个Python进度条库,可以非常方便地在循环中添加进度条。

首先,确保已经安装了tqdm库。如果没有安装,可以使用以下命令进行安装:

pip install tqdm

下面是一个简单的示例代码,演示了如何使用tqdm来显示文件上传的进度:

import requests
from tqdm import tqdm

def upload_file(file_path, target_url):
    total_size = os.path.getsize(file_path)
    with open(file_path, 'rb') as f:
        with tqdm(total=total_size, unit='B', unit_scale=True) as pbar:
            r = requests.post(target_url, data=f, headers={"Content-Type": "application/octet-stream"}, stream=True)
            for chunk in r.iter_content(chunk_size=4096):
                f.write(chunk)
                pbar.update(len(chunk))

# 使用例子
upload_file('path/to/file.txt', 'https://example.com/upload')

在这个例子中,我们使用requests库发送POST请求,将文件逐块上传到目标URL。通过使用tqdm库,我们可以在循环中添加进度条,进而显示上传的进度。

对于文件下载的进度显示,可以使用相似的方法。下面是一个示例代码,演示了如何使用tqdm来显示文件下载的进度:

import requests
from tqdm import tqdm

def download_file(url, save_path):
    response = requests.get(url, stream=True)
    total_size = int(response.headers.get('content-length', 0))
    with open(save_path, 'wb') as f:
        with tqdm(total=total_size, unit='B', unit_scale=True) as pbar:
            for chunk in response.iter_content(chunk_size=4096):
                f.write(chunk)
                pbar.update(len(chunk))

# 使用例子
download_file('https://example.com/file.txt', 'path/to/save/file.txt')

在这个例子中,我们使用requests库发送GET请求来下载文件。同样地,通过使用tqdm库,我们可以在循环中添加进度条,以显示下载的进度。

总结起来,通过使用tqdm库,我们可以非常方便地实现文件上传和下载的进度显示。无论是上传还是下载,都可以使用类似的方式来添加进度条。希望以上示例能够帮助你实现所需的功能。