python - 将zip文件输出到特定目录,而不是脚本目录

标签 python shutil

我正在尝试压缩 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_dirbase_dir 是同一目录,即您要存档的目录。对于更复杂的情况,提供它们是有意义的,这似乎不是您的情况。例如,如果您想进入一个目录,然后通过递归创建子目录的单独存档。

关于python - 将zip文件输出到特定目录,而不是脚本目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55885137/

相关文章:

php - 通过 python 将 JSON 发送到外部 PHP 监听器

python - Scrapy 使用 POST 方法发出请求

python - 经过多次尝试后,我无法使用 Shutil.move 将文件从一个文件夹移动到另一个文件夹

python - 从 gzip 文件写入未压缩文件的内存有效方法

python - Shutil.copytree 的问题

python - 主键列在 sqlalchemy 中不会自动递增(IntegrityError)

python - EPD Python 和 MacPorts Python 可以在 OS X (matplotlib) 上共存吗?

python - functools中lru缓存的使用

move - 在shutil.move 操作期间覆盖目录中已存在的文件

python - 使用 shutil.make_archive() 创建存档同时排除某些路径