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)
import shutil
# creates my_backup.zip
shutil.make_archive("my_backup", "zip", root_dir="./demo")Tar archives
import tarfile
with tarfile.open("demo.tar.gz", "w:gz") as tar:
tar.add("./demo", arcname="demo")Extracting
import zipfile
with zipfile.ZipFile("my_backup.zip") as z:
z.extractall("./restored")Tips
- store archives outside the source folder
- validate extracted size/location
🧪 Try It Yourself
Exercise 1 – List Files with os.listdir
Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.
Output
Press Run to see what your code prints.Exercise 2 – Join Paths with os.path.join
Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.
Output
Press Run to see what your code prints.Exercise 3 – Write and Read a File
Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.
Output
Press Run to see what your code prints.