import time # Import the time module for measuring the execution time
import urllib.request # Import the urllib.request module for downloading files
from urllib.parse import urlparse # Import the urlparse function from urllib.parse for parsing URLs
import os # Import the os module for working with file paths
class download_file:
def __init__(self):
pass
def get_file(self, link):
try:
self.filename = self.get_extension(link) # Get the filename and extension from the link
print("Attempting to download file: " + self.filename[0]) # Print the filename
get = urllib.request.urlopen(link) # Open the URL to download the file
total_size = int(get.headers['Content-Length']) # Get the total size of the file
downloaded_size = 0 # Initialize the downloaded size counter
with open(self.filename[0], "wb") as file: # Open the file for writing in binary mode
print("Total file size: {:.2f} bytes".format(total_size)) # Print the total file size
while True:
buffer = get.read(1024) # Read a chunk of data (1024 bytes) from the URL
if not buffer: # If no more data is read, break the loop
break
downloaded_size += len(buffer) # Increment the downloaded size counter
file.write(buffer) # Write the data to the file
percent = downloaded_size * 100 / total_size # Calculate the download progress percentage
print("Downloaded: {} bytes {:.2f}%".format(downloaded_size, percent), end='\r') # Print the download progress
print("\nDownload complete!") # Print a message indicating that the download is complete
except Exception as err: # Catch any exceptions that occur during the download process
print("Error downloading: " + str(err)) # Print the error message
def get_extension(self, link):
parsed_link = urlparse(link) # Parse the link to extract the filename and extension
filename = os.path.basename(parsed_link.path) # Extract the filename from the parsed link
extension = os.path.splitext(filename)[1] # Extract the extension from the filename
return filename, extension # Return the filename and extension as a tuple
def main():
file_to_download = input("Enter a link to a file to download: ") # Prompt the user to enter a file link
start = time.time() # Record the current time
download = download_file() # Create an instance of the download_file class
download.get_file(file_to_download) # Call the get_file method to download the file
end = time.time() # Record the current time
print("Time taken to download: {:.6f} seconds".format(end - start)) # Print the total execution time
if __name__ == '__main__':
main() # Call the main function if the script is executed directly