如何使用python中的“tqdm”显示在线下载数据时的进度?

2024-09-27 09:34:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我可以找到一些doc来解释如何使用tqdm包,但从中我无法想出如何在在线下载数据时生成进度表。在

下面是我从ResidentMario复制的用于下载数据的示例代码

def download_file(url, filename):
    """
    Helper method handling downloading large files from `url` to `filename`. Returns a pointer to `filename`.
    """
    r = requests.get(url, stream=True)
    with open(filename, 'wb') as f:
        for chunk in r.iter_content(chunk_size=1024): 
            if chunk: # filter out keep-alive new chunks
                f.write(chunk)
    return filename


dat = download_file("https://data.cityofnewyork.us/api/views/h9gi-nx95/rows.csv?accessType=DOWNLOAD",
                    "NYPD Motor Vehicle Collisions.csv")

有人能告诉我如何使用TQM包来显示下载进度吗?在

谢谢


Tags: csvto数据代码url示例docdownload
2条回答

现在我做了一些类似的事情:

def download_file(url, filename):
    """
    Helper method handling downloading large files from `url` to `filename`. Returns a pointer to `filename`.
    """
    chunkSize = 1024
    r = requests.get(url, stream=True)
    with open(filename, 'wb') as f:
        pbar = tqdm( unit="B", total=int( r.headers['Content-Length'] ) )
        for chunk in r.iter_content(chunk_size=chunkSize): 
            if chunk: # filter out keep-alive new chunks
                pbar.update (len(chunk))
                f.write(chunk)
    return filename

多亏了西尔马里尔,但下面的工作对我来说更有意义。在

def download_file(url, filename):
    r = requests.get(url, stream=True)
    filelength = int(r.headers['Content-Length'])

    with open(filename, 'wb') as f:
        pbar = tqdm(total=int(filelength/1024))
        for chunk in r.iter_content(chunk_size=1024):
            if chunk:                   # filter out keep-alive new chunks
                pbar.update ()
                f.write(chunk)

相关问题 更多 >

    热门问题