for url in addresses:
file_name = url.rsplit('/', 1)[-1]
fname_with_path = os.path.join(download_directory, file_name)
attempts = 1
while attempts < 5:
try:
urllib.request.urlretrieve(url, fname_with_path)
print("%-3s %-60s %25s" % ('--', file_name, 'downloaded'), end='')
break
except:
attempts += 1
if attempts > 1 and attempts < 5:
print('tried to download ', file_name, ' attempt:', attempts)
if attempts == 5:
print("%-3s %-60s %25s" % ('--', file_name, 'FAILED'), end='')
pass
这是从URL列表中下载文件的代码的一部分。由于某些文件足够大,我想知道文件的许多KB都是alredy下载的。例如
file1: 348 / 2980
另外,我想在同一行更新进度,而不是像这样:
file1: 348 / 2980
file1: 355 / 2980
file1: 389 / 2980
file1: 402 / 2980
您可以打印回车符(\ r \ n)以覆盖以前的打印输出:另请参阅:How do I write output in same place on the console?
这是你在python 3中打印到同一行的方法:
print('text\r', end='', flush=True)
\r
是回车符并将光标移回到行的开头
我知道它在c / c ++语言中的作用。只需将\r
放在您希望停留在同一位置的行的开头,并在最后删除\n
。
https://github.com/python/cpython/blob/3.7/Lib/urllib/request.py#L283
在您的情况下,似乎urlretrieve
使用reporthook(blocknum, bs, size)
,您可以根据需要覆盖报告代码,例如,如上所述。