'python zipfile module: How to change the structure of zip archive created? [duplicate]

I wrote the following code in order to zip bin_file_path:

 zf = zipfile.ZipFile(file_to_search, mode='w')
 zf.write(bin_file_path)
 zf.close()

If bin_file_path is for example: \dir1\dir2\bin_file, then when I unzip the zip file created, I get a directory named "dir1", inside another directory named "dir2" and only inside "dir2" I'll get the bin_file.

I want that the zip file created contains bin_file directly and not inside of sub_directories. Do you have an idea how to do it?



Solution 1:[1]

You can use

zf = zipfile.ZipFile(file_to_search, mode='w')
zf.write(bin_file_path, custom_name)
zf.close()

where custom_name can be anything including os.path.basename(bin_file_path).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 nwk