shutil make_archive resulting in nested .zip files

2019-04-13 17:58发布

This question already has an answer here:

I've been trying to use make_archive from shutil library.

Here is the code (with comprehensive comments):

from shutil import make_archive
make_archive(
  'zipfile_name', 
  'zip',           # archive format
  root_dir=None,   # current working dir if None
  base_dir=None)   # cwd if None 

Here is an example of directory tree:

folder
│   script.py
└───subfolder1
│   │   file011.txt
│   │   file012.txt
│   │
└───subfolder2
│   │   file011.txt
│   │   file012.txt
│   │
...

If I run my script (with code above), the result is:

folder
│   script.py
└───subfolder1
│   │   file011.txt
│   │   file012.txt
│   │
└───subfolder2
│   │   file011.txt
│   │   file012.txt
│   │
└───zipfile_name.zip
│   │   same content as above (like expected)
│   │   zipfile_name.zip

...

Why is an additional zipfile_name.zip is created? Also, note that the second archive can't be open since it is invalid. I understand if no one has ever faced this issue before, but maybe my parameters are wrong and this is why I'm asking.

1条回答
SAY GOODBYE
2楼-- · 2019-04-13 18:47

I also encountered this problem. Here's a simple trick to solve the issue: use a relative path as the base_name:

from shutil import make_archive
make_archive(
  '../zipfile_name', 
  'zip',           # archive format
  root_dir=None,   # current working dir if None
  base_dir=None)   # cwd if None 

The archive will be created in the parent directory, not interfering with the directory that is being archived.

查看更多
登录 后发表回答