Compressing Files (Zip and Tar archives)
flowchart TD
A["an archive from somewhere else"] --> B["namelist() -- read the names FIRST"]
B --> C{"any entry with .. or a leading /?"}
C -->|yes| D["it is trying to write outside the destination"]
C -->|no| E["extract normally"]
F["zipfile.extractall"] --> G["strips .. and leading slashes -- lands inside"]
H["tarfile.extractall"] --> I["applies the 'data' filter"]
I --> J["raises OutsideDestinationError rather than escaping"]
D --> K["reject the archive; do not 'fix up' the path and continue"]
Zip with shutil (quick)
Section titled “Zip with shutil (quick)”import shutil
# creates my_backup.zip
shutil.make_archive("my_backup", "zip", root_dir="./demo")Tar archives
Section titled “Tar archives”import tarfile
with tarfile.open("demo.tar.gz", "w:gz") as tar:
tar.add("./demo", arcname="demo")Extracting
Section titled “Extracting”import zipfile
with zipfile.ZipFile("my_backup.zip") as z:
z.extractall("./restored")- store archives outside the source folder
- validate extracted size/location
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – List Files with os.listdir
Section titled “Exercise 1 – List Files with os.listdir”Exercise 2 – Join Paths with os.path.join
Section titled “Exercise 2 – Join Paths with os.path.join”Exercise 3 – Write and Read a File
Section titled “Exercise 3 – Write and Read a File”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading