9

I'm trying to zip the contents of a directory, without zipping the directory itself, however I can't find an obvious way to do this, and I'm extremely new to python so it's basically german to me. here's the code I'm using which successfully includes the parent as well as the contents:

#!/usr/bin/env python
import os
import zipfile

def zipdir(path, ziph):
    # ziph is zipfile handle
    for root, dirs, files in os.walk(path):
        for file in files:
            ziph.write(os.path.join(root, file))

if __name__ == '__main__':
    zipf = zipfile.ZipFile('Testing.zip', 'w', zipfile.ZIP_DEFLATED)
    zipdir('android', zipf)
    zipf.close()

I've tried modifying it, but always end up with incomprehensible errors.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Flux
  • 93
  • 1
  • 4

1 Answers1

13

write has second argument - name in archive, ie.

ziph.write(os.path.join(root, file), file)

EDIT:

#!/usr/bin/env python
import os
import zipfile

def zipdir(path, ziph):
    length = len(path)
    
    # ziph is zipfile handle
    for root, dirs, files in os.walk(path):
        folder = root[length:] # path without "parent"
        for file in files:
            ziph.write(os.path.join(root, file), os.path.join(folder, file))

if __name__ == '__main__':
    zipf = zipfile.ZipFile('Testing.zip', 'w', zipfile.ZIP_DEFLATED)
    zipdir('android', zipf)
    zipf.close()

Pathlib solution

from pathlib import Path 

def zipdir(parent_dir : str , ziph : ZipFile) -> None:
    
    for file in Path(parent_dir).rglob('*'): # gets all child items
        ziph.write(file, file.name) 
Umar.H
  • 22,559
  • 7
  • 39
  • 74
furas
  • 134,197
  • 12
  • 106
  • 148
  • You can also use os.path.relpath in order to get a relative path from the absolute path, in case you know the name of the directory from which you want to start. – Elisio Quintino Jul 22 '19 at 14:32