Directory structure inside a ZipFile object

Bulba! bulba at
Thu Dec 9 01:38:46 CET 2004

Hello everyone,

I'm a newbie to Python, learning it and tried to write the script that
would read file, zip it, and put in the target directory. I used
ZipFile module (code below).

It works nice, except the zipfile created contains the directory path
of the source file -- which I do NOT want to recreate. E.g. when
I compress 'c:\\temp\\zz.txt', the resulting zipfile contains not just
'zz.txt' file, but also the whole directory, i.e. first directory
is 'c:', inside of it the directory 'temp' is located, and only then
the 'zz.txt' file is stored.

Changing current directory via os.chdir and then using the
filename itself (zz.txt) doesn't work, i.e. the source directory
structure is still re-created within the zipfile.

Code follows. TIA for reply,

def zf(sfpath, targetdir):
	if (sys.platform[:3] == 'win'):
	zfdir=os.path.dirname(os.path.abspath(targetdir) + tgfpath)
	zfname=zfdir + '\\' + os.path.basename(tgfpath) + '.zip'
	if(not os.path.isdir(zfdir)):
	archive=ZipFile(zfname, 'w', ZIP_DEFLATED)
	print 'zfname ' + zfname

>>> zf('c:\\temp\\zz.txt','c:\\tmp\\test1\\test2')
zfname c:\tmp\test1\test2\temp\

"Cultural ecstasy may have billions of participants, but it hardly
has a single friend." -- Charles Freund

More information about the Python-list mailing list