By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,282 Members | 1,562 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,282 IT Pros & Developers. It's quick & easy.

Directory structure inside a ZipFile object

P: n/a
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'):
tgfpath=sfpath[2:]
else:
tgfpath=sfpath
zfdir=os.path.dirname(os.path.abspath(targetdir) + tgfpath)
zfname=zfdir + '\\' + os.path.basename(tgfpath) + '.zip'
if(not os.path.isdir(zfdir)):
os.makedirs(zfdir)
archive=ZipFile(zfname, 'w', ZIP_DEFLATED)
print 'zfname ' + zfname
archive.write(sfpath)
archive.close()
zf('c:\\temp\\zz.txt','c:\\tmp\\test1\\test2') zfname c:\tmp\test1\test2\temp\zz.txt.zip


--
"Cultural ecstasy may have billions of participants, but it hardly
has a single friend." -- Charles Freund
Jul 18 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Bulba! wrote:
tried to read file, zip it, and put in the target directory....

It works nice, except the zipfile created contains the directory path
of the source file -- which I do NOT want to recreate.

Look into the two-argument form of the write command:

import zipfile
archive = zipfile.ZipFile('box.zip', 'w', zipfile.ZIP_DEFLATED)
archive.write('source/somewhere/one.txt', 'name.txt')
archive.write('two.txt', 'another.txt')
archive.close()

--Scott David Daniels
Sc***********@Acm.Org
Jul 18 '05 #2

P: n/a
On Thu, 09 Dec 2004 07:42:57 -0800, Scott David Daniels
<Sc***********@Acm.Org> wrote:
Look into the two-argument form of the write command:
Well, I should have guessed that, it works. Thanks!

import zipfile
archive = zipfile.ZipFile('box.zip', 'w', zipfile.ZIP_DEFLATED)
archive.write('source/somewhere/one.txt', 'name.txt')
archive.write('two.txt', 'another.txt')
archive.close()

--Scott David Daniels
Sc***********@Acm.Org


--
It's a man's life in a Python Programming Association.
Jul 18 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.