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

Python实现文件复制不覆盖目标文件,支持多实例复制需求

Solution: Copy Files Without Overwriting & Generate Multiple Instances

Let's start by breaking down the key issues in your current code that are causing overwrites and preventing multiple unique file copies:

  • You’re using fixed filenames (\kp.log or \kf.log) every time you copy, so each new copy replaces the existing one.
  • The directory check and copy logic runs inside the log line loop, leading to redundant operations.
  • Windows paths with backslashes can trigger unintended escape characters (e.g., \T in your target path is treated as a tab). Use raw strings or forward slashes to avoid this.
  • The log file isn’t properly closed after reading—using a with statement is safer and cleaner.

Step-by-Step Fix

Here’s how to modify your code to meet your requirements:

  1. Add a helper function for unique filenames
    This function will check if a filename exists in the target directory, and append an incrementing number (like kp_1.log, kp_2.log) until it finds an unused name.

  2. Simplify directory setup
    Only create the target directory once, outside the log loop, to avoid redundant checks.

  3. Adjust copy logic
    Determine the base filename (kp/kf) based on your log logic, generate a unique version of that name, then copy the file without overwriting.

Modified Code

import os
import shutil

# Use raw strings for Windows paths to avoid escape character issues
target_dir = r'C:\DIST\WR_4.5\Test'
source_log = r'C:\DIST\WR_4.5\oHistory2.log'
pass_text = 'Test End'

def get_unique_filename(target_dir, base_name):
    """Generate a unique filename to avoid overwriting existing files."""
    name, ext = os.path.splitext(base_name)
    counter = 1
    unique_name = base_name
    # Loop until we find a filename that doesn't exist
    while os.path.exists(os.path.join(target_dir, unique_name)):
        unique_name = f"{name}_{counter}{ext}"
        counter += 1
    return unique_name

def check_and_copy():
    # Create target directory if it doesn't exist (no error if it does)
    os.makedirs(target_dir, exist_ok=True)
    
    # Read log file safely with a 'with' statement (auto-closes after use)
    with open(source_log, 'r') as log:
        # Check if pass_text appears anywhere in the log to set base filename
        base_name = 'kp.log' if any(pass_text in line for line in log) else 'kf.log'
    
    # Get a unique version of the base filename
    target_filename = get_unique_filename(target_dir, base_name)
    target_path = os.path.join(target_dir, target_filename)
    
    # Copy the file (preserves metadata like creation time)
    shutil.copy2(source_log, target_path)
    print(f"Successfully copied to: {target_path}")

if __name__ == "__main__":
    check_and_copy()

Key Details:

  • get_unique_filename: This handles the core requirement of avoiding overwrites. For example, if kp.log already exists, it will generate kp_1.log, then kp_2.log, and so on.
  • os.makedirs(target_dir, exist_ok=True): Replaces your manual directory check—it creates the directory if needed, and does nothing if it already exists (no errors thrown).
  • with open(...) as log: Ensures the log file is properly closed even if an error occurs during reading.
  • any(pass_text in line for line in log): Efficiently checks if your pass_text appears anywhere in the log, then sets the base filename accordingly.

If You Need to Copy for Every Matching Line

If your goal was to copy the log file every time pass_text appears in a line (not just once based on its presence), adjust the loop like this:

def check_and_copy():
    os.makedirs(target_dir, exist_ok=True)
    
    with open(source_log, 'r') as log:
        for line_num, line in enumerate(log, 1):
            # Set base filename per line
            base_name = 'kp.log' if pass_text in line else 'kf.log'
            # Get unique name for each copy
            target_filename = get_unique_filename(target_dir, base_name)
            target_path = os.path.join(target_dir, target_filename)
            shutil.copy2(source_log, target_path)
            print(f"Copied line {line_num} to: {target_path}")

This will create a unique file for every line in the log, using kp.log or kf.log as the base depending on the line content.

内容的提问来源于stack exchange,提问作者Exitl0l

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:39:32