2

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)
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
massu1000
  • 209
  • 2
  • 10

1 Answers1

2

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).

CristiFati
  • 38,250
  • 9
  • 50
  • 87