使用shutil.make_archive压缩文件异常:压缩包内含损坏文件
shutil.make_archive Oh I’ve run into this exact problem before! Let’s break down what’s happening and get it fixed.
Root Cause
The core issue here is that your output zip file is being created inside the directory you’re trying to compress. When shutil.make_archive runs, it attempts to archive the entire C:\Users\test folder—including the partially written zip file that’s being generated there. This circular write/read operation leads to the corrupted zip_file entry in your final archive.
Solutions
1. Save the Archive Outside the Target Directory
The first argument to make_archive is the base path of your output file (without the extension). Instead of using a relative name like zip_file (which defaults to your current working directory), specify an absolute path that’s outside the folder you’re compressing.
Example:
import shutil # Save the zip to your Users folder, not inside the test folder shutil.make_archive(r'C:\Users\zip_file', 'zip', r'C:\Users\test')
Pro tip: Use raw strings (r'path') for Windows paths to avoid escape character headaches.
2. Archive Folder Contents (Not the Folder Itself)
If you don’t want the test folder to be the top-level entry in your zip, use the base_dir parameter to target the folder’s contents directly. This also helps avoid accidental inclusion of the output zip if you’re careful with the save path.
Example:
import shutil target_dir = r'C:\Users\test' # Save the zip outside the target directory, and archive just its contents shutil.make_archive(r'C:\Users\zipfile_name', 'zip', root_dir=target_dir, base_dir=target_dir)
When you open this zip, you’ll see all files/subfolders from test directly, rather than wrapped inside a test folder.
Your second code snippet likely worked because either:
- You saved the archive outside the target directory, or
- The
base_dirparameter prevented the tool from archiving the parent folder (and thus the zip file being created).
内容的提问来源于stack exchange,提问作者Drake .C

