Skip to content
Advertisement

How to avoid subfolders creation while zipping files?

I am trying to zip the files from the list localpath_list in to one zip file `reports.zip.

It works as expected, but when I extract the reports.zip file, there are folders created inside it.

i.e all the .xls files are under files/sample/.

what I need is just the .xls files without any folder structure.

localpath_list = ["files/sample/sample1.xls", "files/sample/sample2.xls", "files/sample/sample3.xls"]
with zipfile.ZipFile(fr"downloads/reports.zip", 'w') as zipF:
    for file in localpath_list:
        zipF.write(file, compress_type=zipfile.ZIP_DEFLATED)

Advertisement

Answer

According to: [Python.Docs]: zipfile – ZipFile.write(filename, arcname=None, compress_type=None, compresslevel=None) (emphasis is mine):

Write the file named filename to the archive, giving it the archive name arcname (by default, this will be the same as filename, …

So you should use:

zipF.write(file, arcname=os.path.basename(file), compress_type=zipfile.ZIP_DEFLATED)

If expanding the functionality (to include files from multiple folders) is in plan, you should pay attention to duplicate file base names (in different folders).

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement