如何在下载之前获得正确的gzip文件大小



目前,我正在尝试从网站下载压缩数据集gzip文件,并使用tqdm库来显示下载进度。然而,我注意到tqdm进度条将溢出,原因是响应标头中"Content-Length"的文件大小不准确。我将粘贴下面的示例代码作为参考:

import requests
from tqdm import tqdm
url = 'https://www.cs.cmu.edu/~./enron/enron_mail_20150507.tar.gz'
filename = url.split('/')[-1]
with requests.get(url, stream=True) as req:
with open(filename, 'wb') as file:
print('downloading the Enron dataset')
total_size = int(req.headers['Content-Length'])
print(req.headers)
progress = tqdm(total=(total_size),
unit='iB', unit_scale=True, unit_divisor=1024, ascii=' █',
bar_format='{l_bar}{bar:50}{r_bar}{bar:-50b}')
for chunk in req.iter_content(chunk_size=1024):
if chunk:
progress.update(len(chunk))
file.write(chunk)
print('download complete!')

我做了一些搜索,但找不到解决这个问题的好办法。有什么方法可以预先确定需要下载的gzip文件大小吗?或者有什么解决问题的建议吗?

import requests
from hurry.filesize import size
headers = {'accept-encoding': ''}

def main(url):
r = requests.head(url, headers=headers)
cl = int(r.headers['Content-Length'])
print(size(cl))

main("https://www.cs.cmu.edu/~./enron/enron_mail_20150507.tar.gz")

输出:

422M

有另一种方法可以查找大小。但这种方法不能用于你的文件,因为它可能需要很长时间(我想(。它是:

res = requests.get('https://www.cs.cmu.edu/~./enron/enron_mail_20150507.tar.gz')
file_size = len(res.content)

编辑
找到了一个解决方案:

file_size = int(requests.head('https://www.cs.cmu.edu/~./enron/enron_mail_20150507.tar.gz', headers={'accept-encoding': ''}).headers['Content-Length'])

最新更新