Reputation: 9856
I'm experimenting with the zipfile module of python the code i currently use is this:
z = zipfile.ZipFile("jar/algorithms.jar", "w")
z.write('directory/QuickSort.class')
The problem is that my file is added to the jar as following:
algorithms.jar>directory>QuickSort.class
What I want is: algorithms.jar>QuickSort.class
How can I achieve this?
Upvotes: 3
Views: 6861
Reputation: 11460
Consider the following example. This will create a zipped archive of a folder in that same folder and remove the directory structure from the zipped output file.
import os
import zipfile
mydir = r'c:\temp\filestozip' #all the files in this directory will be archived
zf = zipfile.ZipFile(mydir + '\\myzipfile.zip', "w")
for dirname, subdirs, files in os.walk(mydir):
for filename in files:
if not filename.endswith('.zip'): #
zf.write(os.path.join(dirname, filename),arcname=filename)
zf.close()
Upvotes: 0
Reputation: 1976
You can supply the name you want the file to have in the archive as the second parameter to write
like this:
In [39]: z = zipfile.ZipFile("jar/algorithms.jar", "w")
In [40]: z.printdir()
File Name Modified Size
In [41]: z.write("directory/QuickSort.class", "QuickSort.class")
In [42]: z.printdir()
File Name Modified Size
QuickSort.class 2011-08-10 15:26:47 0
In [43]: z.close()
Also see the zipfile documentation.
Upvotes: 0
Reputation: 8362
You can use the arcname parameter - see http://docs.python.org/library/zipfile.html#zipfile.ZipFile.write
z.write("directory/QuickSort.class","QuickSort.class")
Upvotes: 7