pythonzip

Extract a zip file and save the content to disc instead


I have to following code snippet originating from the garminconnect python wrapper

activities = api.get_activities_by_date(
            start_date.isoformat(), end_date.isoformat(), 'other')

for activity in activities:
     activity_id = activity["activityId"]
     zip_data = api.download_activity(
                    activity_id, dl_fmt=api.ActivityDownloadFormat.ORIGINAL
                )
     output_file = f"./{str(today)}.zip"
     with open(output_file, "wb") as fb:
         fb.write(zip_data)

It works so far and saves the zip file as intended. But instead of saving the zip file directly i want to unpack it with out writing it to disk and save the content (a .fit file which will be named "activityId.fit" by default).

Ideally i would like to rename it aswell to f"./{str(today)}.fit"

What is fasted and most pythonic way to achieve this?

Thanks for any help in advance!!


Solution

  • import io
    from zipfile import ZipFile
        
    activities = api.get_activities_by_date(
                start_date.isoformat(), end_date.isoformat(), 'other')
    
    for activity in activities:
         activity_id = activity["activityId"]
         fit_contents = None
         zip_data = api.download_activity(
                        activity_id, dl_fmt=api.ActivityDownloadFormat.ORIGINAL
                    )
         with io.BytesIO(zip_data) as byte_stream:
            with ZipFile(byte_stream) as myzip:
                with myzip.open('activityId.fit') as fit_file:
                    fit_contents = fit_file.read()
    
         output_file = f"./{str(today)}.fit"
         with open(output_file, "wb") as fb:
             fb.write(fit_contents)