I want to download a file from the release page of a GitHub repository. I do not know how to do this. Currently my code is
#import libraries
import requests
import zipfile
import io
#define the link to the latest GTNH version
GTNHLink = "https://github.com/GTNewHorizons/GT-New-Horizons-Modpack/releases/latest"
#get the path to the old file
OriginalFilePath = "C:\\Users\\********\\CurseforgeUtils\\GTNHAutoUpdate\\GTNHOld.zip"
#download and save the new file
NewFileContent = requests.get(GTNHLink)
NewFile = zipfile.ZipFile(io.BytesIO(NewFileContent.content))
NewFile.close
but (I assume) because there are multiple files on the page it's not giving me the zip file I want. How do I fix this? The main issue I found with it is that the file name is going to change as new versions are released.
You can get the list of release files in the assets
field, then you can iterate through the list to find the .zip
file using asset['name'].endswith('.zip')
.
response = requests.get(GTNHLink)
if response.status_code == 200:
release_data = response.json()
assets = release_data.get('assets', [])
for asset in assets:
if asset['name'].endswith('.zip'):
download_url = asset['browser_download_url']
file_response = requests.get(download_url)
with open(OriginalFilePath, "wb") as file:
file.write(file_response.content)
break