Greetings, I am trying to compress an XML file in ZIP format for which I give it the absolute path, my code:
import os
import zipfile
PATH_XML = 'media/Facturacion/miarchivo.xml'
PATH_COMPLETO_XML = os.path.join(os.path.dirname(os.path.dirname(__file__)),PATH_XML)
PATH_ZIP = 'media/Facturacion/archivozipnuevo.zip'
PATH_COMPLETO_ZIP = os.path.join(os.path.dirname(os.path.dirname(__file__)),PATH_ZIP)
zipfile.ZipFile(PATH_COMPLETO_ZIP, mode='w').write(PATH_COMPLETO_XML)
This code does indeed compress the final file but with all the subdirectories it finds in that path, and I just want it to contain that final file.
Thanks for your suggestions..!!
To prevent it from generating the entire file tree structure, you must use the
arcname
method argumentzipfile.ZipFile.write
and pass the name of the file to include:If you don't specify an absolute path
filename
, it is treated as a path relative to the current working directory. The entire file structure from that working directory up to the file we want to include is reproduced in the zip (if not specifiedarcname
). If you assign an absolute path, the same thing happens, but generating the entire file structure of the absolute path.So obviously if you change the working directory (
os.chdir
) of your process to the one containing the file to include (media/Facturacion
), you canfilename
just pass the filename ("miarchivo.xml"
) and you don't needarcname
.