Search code examples
pythonvariablesinputhyperlinkunzip

run download link and unzip to a folder in python with a url that stores a variable


How could a script in python be made that, through a value entered by the user through the console in an input, is replaced in a specific url of a repository to be able to download a .zip and when it is downloaded automatically, a folder is created where it is entered and would unpack, for example:

Given two random github urls:

https://github.com/exercism/python/archive/refs/heads/bobahop-patch-1.zip

https://github.com/exercism/python/archive/refs/heads/bobahop-patch-2.zip

The user could enter "patch-1" or "patch-2" by console and this value would be replaced in the url and in turn the link would be executed and the .zip it contains would be downloaded to the repository. Simultaneously, a folder with any name would be created (the value entered by the user in the console, for example) and the downloaded .zip would be moved to that folder and once there it would be decompressed.


Solution

  • Python has

    • standard module urllib to get/download data from web page urllib.request.urlretrieve()
    • standard moduel os to create folder os.makedirs() and move/rename file os.rename()
    • standard module zipfile to compress/uncompress .zip file
    import os
    import urllib.request
    import zipfile
    
    #user_input = input("What to download: ")
    user_input = 'patch-1'
    
    pattern = 'https://github.com/exercism/python/archive/refs/heads/bobahop-{}.zip'
    url = pattern.format(user_input)
    
    filename = f"{user_input}.zip"
    
    print('From:', url)
    print('  To:', filename)
    
    urllib.request.urlretrieve(url, filename)
    
    # ---
    
    destination_folder = user_input
    print('Create folder:', destination_folder)
    
    os.makedirs(destination_folder, exist_ok=True)
    
    # ---
    
    print('Uncompress')
    
    zip_file = zipfile.ZipFile(filename)
    zip_file.extractall(destination_folder)
    
    # ---
    
    print("Move .zip to folder")
    
    old_name = filename
    new_name = os.path.join(destination_folder, filename)
    os.rename(old_name, new_name)