gpt4 book ai didi

python - 基于固定相对路径在 zip 文件中包含目录结构

转载 作者:太空宇宙 更新时间:2023-11-03 15:53:13 25 4
gpt4 key购买 nike

给定路径 a:\\b\\c\\d\\e 处的目录,我想在 python 3.5+ 中创建一个如下所示的 zip 文件:

file.zip # want this
+d
+-...files from d\
+-e
+-...files from e\

我通过使用 oszipfile 遍历目标路径来尝试此操作:

start_path = "a:\\b\\c\\d"

for root, dirs, files in os.walk(start_path):
for file in files:
ziph.write(os.path.relpath(os.path.join(root, file)))

由于 relpath 和工作目录位于 b 中,代码将创建一个 zip 文件,如下所示:

file.zip # do not want this
+c
+-...files from c\
+-d
+-...files from d\
+-e
+-...files from e\

我的问题是:如何强制 zipwriter 创建如开头所示的目录结构,以 dir d 开头,而我只在运行时知道完整路径。

最佳答案

ZipFile.write 接受 second parameter ,这是您希望它位于 zip 内的目录。所以你可以有这样的东西:

start_path = "a:\\b\\c\\d"
import os
zip_start_path = start_path.split(os.sep)[-1]

关于python - 基于固定相对路径在 zip 文件中包含目录结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41061714/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com