zipping files in python without folder structure

Question:

I want to create a zip file of some files somewhere on the disk in python. I successfully got the path to the folder and each file name so I did:

with zp(os.path.join(self.savePath, self.selectedIndex + ".zip"), "w") as zip:
                for file in filesToZip:
                    zip.write(self.folderPath + file)

Everything works fine, but the zipfile that is output contains the entire folder structure leading up to the files. Is there a way to only zip the files and not the folders with it?

Asked By: Rouben

||

Answers:

From the documentation:

ZipFile.write(filename, arcname=None, compress_type=None,
compresslevel=None)

Write the file named filename to the archive, giving it the archive
name arcname (by default, this will be the same as filename, but
without a drive letter and with leading path separators removed).

So, just specify an explicit arcname:

with zp(os.path.join(self.savePath, self.selectedIndex + ".zip"), "w") as zip:
                for file in filesToZip:
                    zip.write(self.folderPath + file, arcname=file)
Answered By: larsks

Maybe I’ misunderstand the question but could someone explain to me why the answer is not:

zip.write(file, arcname=os.path.basename(file))

It works for me but, again, I might be missing something in the question…

Answered By: Malachi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.