I am trying to figure out how to check if a download has been completed. Basically I want it to wait until the file is finished downloading then print: Download completed.
Here is my current code and what I am trying to do with it:
from urllib import request
print("Are you sure you want to download the newest file? y/n")
answer = input()
while True:
if answer == 'y':
print("Downloading file...")
downloading = True
request.urlretrieve("FILE_URL", "FILE_NAME")
elif answer == 'n':
exit()
else:
print("That is not a valid answer, please answer with y/n.")
answer = input()
#I need some sort of function here that checks if the file is still being
#downloaded
when downloading == False:
print("Download Completed.")
When urlretrieve
returns, the file has already finished downloading.
See the usage example from the docs :
>>> import urllib.request
>>> local_filename, headers = urllib.request.urlretrieve('http://python.org/')
>>> html = open(local_filename)
As can be seen, the file is opened immediately after the call to urlretrieve
, as it was already created and the content was already written there.
If you use the urllib.request.urlretrieve
reporthook
option, you can monitor the progress of the download, especially useful with large files, like so:
import urllib.request
def Download_Progress(block_num, block_size, total_size):
downloaded = block_num * block_size
progress = int((downloaded/total_size)*100)
print ("Download Progress",str(progress),"%")
url = "https://somesite/some.pdf"
urllib.request.urlretrieve(url, 'mycopy.pdf', reporthook=Download_Progress)
print ("Finished")
You can achieve something similar with the requests
package as well.
import requests
url = "https://somesite/some.pdf"
#Get the headers of the remote file
h = requests.head(url, allow_redirects=True)
#Get the size of the file
total_size = int(h.headers.get('content-length'))
#Request the file download with stream set to True
r = requests.get(url, stream=True)
#Open a local file for writing
localfile = open("mycopy.pdf", "wb")
chunks = 0
#Process the file as it arrives
for chunk in r.iter_content(chunk_size=512):
if chunk:
chunks += 1
downloaded = chunks * 512
# An approximation as the chunks don't have to be 512 bytes
progress = int((downloaded/total_size)*100)
print ("Download Progress",str(progress),"%")
localfile.write(chunk)
print("Finished")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.