python zipfile 模块:如何更改创建的 zip 存档的结构?

python zipfile module: How to change the structure of zip archive created?

我为了压缩写了下面的代码bin_file_path:

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

如果 bin_file_path 例如:\dir1\dir2\bin_file,那么当我解压缩创建的 zip 文件时,我得到一个名为 "dir1" 的目录,在另一个名为 "dir2" 的目录中只有在 "dir2" 内,我才能得到 bin_file。

我希望创建的 zip 文件直接包含 bin_file 而不是 sub_directories 内部。你知道怎么做吗?

您可以使用

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

其中 custom_name 可以是任何内容,包括 os.path.basename(bin_file_path).