recursion - Recursively append files to zip archive in python -


in python 2.7.4 on windows, if have directory structure follows:

test/foo/a.bak test/foo/b.bak test/foo/bar/c.bak test/d.bak 

and use following add them existing archive such 'd.bak' @ root of archive:

import zipfile import os.path import fnmatch  def find_files(directory, pattern):     root, dirs, files in os.walk(directory):         basename in files:             if fnmatch.fnmatch(basename, pattern):                 filename = os.path.join(root, basename)                 yield filename  if __name__=='__main__':     z = zipfile.zipfile("testarch.zip", "a", zipfile.zip_deflated)      filename in find_files('test', '*.*'):         print 'found file:', filename         z.write(filename, os.path.basename(filename), zipfile.zip_deflated)      z.close() 

the directory of zip file flat. creates foo/ directory only if sub-directory exists in (if exclude test/foo/bar/c.bak, not create directory. if included, foo/ created not foo/bar/ if makes sense), no sub-directories or files:

foo/ a.bak b.bak c.bak d.bak 

am missing something?

the problem you're explicitly asking flatten paths:

z.write(filename, os.path.basename(filename), zipfile.zip_deflated) 

if @ the docs, default arcname is:

the same filename, without drive letter , leading path separators removed

but you're overriding os.path.basename(filename). (if don't know basename does, returns "the last pathname component". if don't want last pathname component, don't call basename.)

if z.write('test/foo/bar/c.bak'), create zip entry named test/foo/bar/c.bak, if z.write('test/foo/bar/c.bak', 'c.bak'), create zip entry named c.bak. since of entries, whole thing ends flattened.


Comments

Popular posts from this blog

android - getbluetoothservice() called with no bluetoothmanagercallback -

sql - ASP.NET SqlDataSource, like on SelectCommand -

ios - Undefined symbols for architecture armv7: "_OBJC_CLASS_$_SSZipArchive" -