You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用zipfile压缩指定路径特定文件时覆盖问题的解决方法

Fixing the DB.zip Overwrite Issue

Alright, let's tackle this problem head-on. The core issue here is that your current code overwrites the DB.zip file every time it finds a matching file. Here's why: you're using the "w" (write) mode for ZipFile inside the loop—this mode creates a brand new archive (or wipes an existing one) each time you call it, so all previous files get erased, leaving only the last one you processed.

Let's go through two solid solutions, starting with the most reliable approach.

Solution 1: Collect Valid Files First, Then Compress All at Once

This method is cleaner and avoids overwrite issues entirely. We'll first gather all files that meet your criteria, then package them into the zip archive in one go.

Here's the revised code:

import os
import zipfile

pr_directory = r'C:\Users\vijo9001\Desktop\Infact'
zip_file_path = os.path.join(pr_directory, 'DB.zip')
target_keywords = {"AAA", "BBB", "CCC"}

# Step 1: Gather all files that match our rules
valid_files = []
for filename in os.listdir(pr_directory):
    # Make sure we're dealing with a file (not a folder)
    file_full_path = os.path.join(pr_directory, filename)
    if not os.path.isfile(file_full_path):
        continue
    
    # Skip files with "SFF" in the name
    if "SFF" in filename:
        continue
    
    # Check if the file contains any of our target keywords
    for keyword in target_keywords:
        if keyword in filename:
            valid_files.append(filename)
            break  # No need to check other keywords once we find a match

# Step 2: Compress all valid files into DB.zip
if valid_files:
    # Use a `with` statement to auto-close the zip file (safer than manual close())
    with zipfile.ZipFile(zip_file_path, "w", zipfile.ZIP_DEFLATED) as zip_archive:
        for file in valid_files:
            zip_archive.write(file)
    print(f"Success! Compressed {len(valid_files)} files into DB.zip")
else:
    print("No files matched your criteria.")

Key improvements here:

  • Avoids repeated overwrites: We only create the zip archive once, adding all valid files in a single operation.
  • Safer path handling: Uses os.path.join() to build paths (works across Windows/macOS/Linux instead of hardcoding /).
  • Auto-manages zip resources: The with statement automatically closes the zip file when done, so you don't have to remember to call zip.close().
  • Clearer logic: Separates file filtering from compression, making the code easier to debug and modify later.

Solution 2: Append Files to the Zip (Alternative Approach)

If you prefer to process files one by one and append them to the zip, you can use the "a" (append) mode. Just note: you'll want to delete any existing DB.zip first to avoid mixing old and new files.

Here's how that looks:

import os
import zipfile

pr_directory = r'C:\Users\vijo9001\Desktop\Infact'
zip_file_path = os.path.join(pr_directory, 'DB.zip')
target_keywords = {"AAA", "BBB", "CCC"}

# Delete existing DB.zip if it exists (start fresh)
if os.path.exists(zip_file_path):
    os.remove(zip_file_path)

for filename in os.listdir(pr_directory):
    file_full_path = os.path.join(pr_directory, filename)
    if not os.path.isfile(file_full_path):
        continue
    
    if "SFF" in filename:
        continue
    
    for keyword in target_keywords:
        if keyword in filename:
            # Use "a" mode to append to the zip (creates it if it doesn't exist)
            with zipfile.ZipFile(zip_file_path, "a", zipfile.ZIP_DEFLATED) as zip_archive:
                zip_archive.write(filename)
            break

Note about this approach:

  • The "a" mode will add files to an existing zip, so deleting the old zip first ensures you get a clean archive every time.
  • This is okay for small numbers of files, but the first solution is more efficient since it opens/closes the zip file only once.

内容的提问来源于stack exchange,提问作者João Vieira

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:00:03