How to create an empty zip file?
Asked Answered
A

3

16

I'm using zipfile and under some circumstance I need to create an empty zip file for some placeholder purpose. How can I do this?

I know this:

Changed in version 2.7.1: If the file is created with mode 'a' or 'w' and then closed without adding any files to the archive, the appropriate ZIP structures for an empty archive will be written to the file.

but my server uses a lower version as 2.6.

Analeptic answered 8/8, 2014 at 3:6 Comment(0)
S
22

You can create an empty zip file without the need to zipfile as:

empty_zip_data = b'PK\x05\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

with open('empty.zip', 'wb') as zip:
    zip.write(empty_zip_data)

empty_zip_data is the data of an empty zip file.

Staw answered 8/8, 2014 at 3:25 Comment(1)
For Python 3 use empty_zip_data = b'PK\x05....Douty
P
12

You can simply do:

from zipfile import ZipFile
archive_name = 'test_file.zip'
with ZipFile(archive_name, 'w') as file:
  pass
Printing answered 20/5, 2019 at 18:49 Comment(2)
Downvoted as this does not produce a readable ZipFile (zipfile.BadZipFile: File is not a zip file)Pisarik
Works for me on Linux and Windows and on Python 3.8 and Python 3.9. The created zip file is a valid ZIP file in Python and in 7-Zip.Cath
M
1

If on Linux:

echo 504b0506000000000000000000000000000000000000 | xxd -r -p > empty.zip

Marianomaribel answered 4/10, 2023 at 8:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.