我正在尝试压缩 src
的内容文件夹并将 zip 文件保存在 dst
中文件夹:
import shutil
src = '/home/bart/python_projects/testenv/sampler_proj/sampler/media/audio/slices/'
dst = '/home/bart/python_projects/testenv/sampler_proj/sampler/media/audio/zipped/'
shutil.make_archive('samples', 'zip', base_dir=src, root_dir=dst)
但是,samples.zip
文件未保存到 dst
文件夹,但到我的脚本所在的文件夹,即 /home/bart/python_projects/testenv/sampler_proj/sampler/media/audio/
.
如何修复它?
我查看了其他一些 SO 线程和 shutil
文档,但是 root_dir
的定义和base_dir
非常困惑。
最佳答案
根据the docs :
shutil.make_archive(base_name, format[, root_dir[, base_dir[, verbose[, dry_run[, owner[, group[, logger]]]]]]])
Create an archive file (such as zip or tar) and return its name.
base_name is the name of the file to create, including the path, minus any format-specific extension. format is the archive format: one of “zip” (if the zlib module is available), “tar”, “gztar” (if the zlib module is available), “bztar” (if the bz2 module is available), or “xztar” (if the lzma module is available).
(粗体字是我的)。
如果您不希望文件位于当前目录中,第一个参数应包含完整的目标路径。
所以我猜你给 root_dir
分配了一个错误的目录。根据文档,root_dir
应该是:
root_dir is a directory that will be the root directory of the archive; for example, we typically chdir into root_dir before creating the archive.
尝试做:
src = '/home/bart/python_projects/testenv/sampler_proj/sampler/media/audio/slices/'
dst = '/home/bart/python_projects/testenv/sampler_proj/sampler/media/audio/zipped/'
pth = os.path.join(dst, 'samples')
shutil.make_archive(pth, 'zip', root_dir=src, base_dir=src)
在大多数情况下,root_dir
和 base_dir
是同一目录,即您要存档的目录。对于更复杂的情况,提供它们是有意义的,这似乎不是您的情况。例如,如果您想进入一个目录,然后通过递归创建子目录的单独存档。
关于python - 将zip文件输出到特定目录,而不是脚本目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55885137/