Skip to content

Compressing Files (Zip and Tar archives)

diagram extracting an archive you did not create mermaid
An archive is a list of names chosen by whoever built it, and those names can point outside the directory you are extracting into. Python's zipfile normalises them away; tarfile historically did not, which is why modern versions apply a filter and refuse. Either way the rule for anything downloaded is to look at the names before extracting.
make_zip.py
import shutil
 
# creates my_backup.zip
shutil.make_archive("my_backup", "zip", root_dir="./demo")
make_tar.py
import tarfile
 
with tarfile.open("demo.tar.gz", "w:gz") as tar:
    tar.add("./demo", arcname="demo")
extract_zip.py
import zipfile
 
with zipfile.ZipFile("my_backup.zip") as z:
    z.extractall("./restored")
  • store archives outside the source folder
  • validate extracted size/location

Exercise 2 – Join Paths with os.path.join

Section titled “Exercise 2 – Join Paths with os.path.join”

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading