1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| #!/usr/bin/python
# -*- coding: utf-8 -*-
# Python 3
import os
import zipfile
from fnmatch import fnmatch
#############################################################################
def repertoirezip(repertoire, archive, premier=True, mode="w", inclusfics="*", exclusreps="", repvide=True):
"""zippe l'arborescence complète du répertoire dans le fichier .zip
archive avec des chemins relatifs.
- premier: si True, met le 1er répertoire comme racine de l'arborescence
- mode: "w" (nouvelle archive) ou "a" (ajout à l'archive existante)
- inclusfics: motifs "wildcard" d'inclusion des fichiers (séparateur=';')
- exclusreps: motifs "wildcard" d'exclusion des répertoires (sép.=';')
- repvide: si True, crée aussi les sous-répertoires vides
Retourne la liste des éventuelles erreurs de os.walk
"""
erreurs = [] # pour contenir les erreurs de os.walk
inclusfics, exclusreps = inclusfics.split(';'), exclusreps.split(';')
repertoire = os.path.abspath(os.path.expanduser(repertoire))
baserep = os.path.dirname(repertoire) if premier else repertoire
with zipfile.ZipFile(archive, mode, zipfile.ZIP_DEFLATED, True) as zf:
if premier: # écriture du 1er répertoire base de l'arborescence
zf.write(repertoire, os.path.relpath(repertoire, baserep))
for rep, sreps, fics in os.walk(repertoire, onerror=erreurs.append):
# retire les sous-répertoires qui matchent avec exclusreps
for srep in sreps[:]:
if [True for motif in exclusreps if fnmatch(srep, motif)]:
sreps.remove(srep)
# crée le répertoire, même s'il est vide si c'est demandé
if rep!=repertoire and repvide:
zf.write(rep, os.path.relpath(rep, baserep))
# archive les fichiers qui matchent avec inclusfics
for fic in fics:
if [True for motif in inclusfics if fnmatch(fic, motif)]:
fichier = os.path.join(rep, fic)
zf.write(fichier, os.path.relpath(fichier, baserep))
return erreurs |
Partager