如果您想要复制一个文件夹及其所有子文件夹中的文件,并且要保留相同的文件名但避免文件名冲突,您可以使用以下Python脚本:
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("复制完成")