Python Central HubSign in

Automation and Scripting / Phase 1: OS & File System Automation

Compressing Files (Zip and Tar archives)

Create and extract zip/tar archives using shutil and tarfile/zipfile.

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.

Zip with shutil (quick)

Python
import shutil
 
# creates my_backup.zip
shutil.make_archive("my_backup", "zip", root_dir="./demo")

Tar archives

Python
import tarfile
 
with tarfile.open("demo.tar.gz", "w:gz") as tar:
    tar.add("./demo", arcname="demo")

Extracting

Python
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

exerciseYour turn

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

exerciseYour turn

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

exerciseYour turn

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.

Was this page helpful?

Let us know how we did