0

I am having a situation in ensuring that when I create a zip file it does not have the whole directory of the file when it is unzipped.

Having done some research there is a lot of content about using arcname in zip.write, however any solution I try results in the whole server being zipped!

I have tried adding arcname = os.path.basename(file) and other possible solutions with no luck.

This is my code below:

all_order_files = glob.glob("/directory/"+str(order_submission.id)+"-*")

zip = zipfile.ZipFile("/directory/" + str(order_submission.id) + '-Order-Summary.zip', 'w')

for file in all_order_files:
    zip.write(file)

zip.close()
Alex Stewart
  • 730
  • 3
  • 12
  • 30

1 Answers1

0

After reading this answer: Create .zip in Python?

I adapted the code to read the following which solved the issue for me.

    all_order_files = glob.glob("/directory/"+str(order_submission.id)+"-*")

    zip = zipfile.ZipFile("/directory/" + str(order_submission.id) + '-Order-Summary.zip', 'w')

    path = "/directory/"

    for file in all_order_files:
        file_name = file.split('/')[-1]

        absname = os.path.abspath(os.path.join(path, file_name))
        arcname = absname[len(path) + 1:]
        zip.write(absname, arcname)

    zip.close()

Noting the extra argument provided to the write function that changes the directory structure when the zip file is unzipped.

Alex Stewart
  • 730
  • 3
  • 12
  • 30