MAC copy file problem: Copy files (containing the same file name)

If you want to copy the files in a folder and all its subfolders, and you want to keep the same file names but avoid file name conflicts, you can use the following Python script:

import os
import shutil

source_folder = '/源文件夹路径/'
target_folder = '/目标文件夹路径/'

for root, dirs, files in os.walk(source_folder):
    for filename in files:
        source_file = os.path.join(root, filename)
        relative_path = os.path.relpath(source_file, source_folder)
        target_file = os.path.join(target_folder, relative_path)

        if os.path.exists(target_file):
            # 如果目标文件已存在,添加一个后缀来避免冲突
            base, ext = os.path.splitext(filename)
            counter = 1
            while os.path.exists(target_file):
                new_filename = f"{
      
      base}_{
      
      counter}{
      
      ext}"
                target_file = os.path.join(target_folder, relative_path.replace(filename, new_filename))
                counter += 1

        os.makedirs(os.path.dirname(target_file), exist_ok=True)
        shutil.copy2(source_file, target_file)

print("复制完成")

Guess you like

Origin blog.csdn.net/haimengjie/article/details/132765462