SpacetySliceTools/tools/copymatchfile.py

57 lines
2.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import os
import shutil
def copy_matching_files(folder_A, folder_B, folder_C):
"""
将文件夹A和文件夹B中同名的文件复制到文件夹C
参数:
folder_A: 第一个文件夹路径
folder_B: 第二个文件夹路径
folder_C: 目标文件夹路径
"""
# 确保目标文件夹存在
if not os.path.exists(folder_C):
os.makedirs(folder_C)
print(f"创建目标文件夹: {folder_C}")
try:
# 获取两个文件夹中的文件列表(不包含目录)
print("A")
files_A = [f for f in os.listdir(folder_A) if os.path.isfile(os.path.join(folder_A, f))]
print("A")
files_B = [f for f in os.listdir(folder_B) if os.path.isfile(os.path.join(folder_B, f))]
print(files_B)
# 找出两个文件夹中同名的文件
common_files = set(files_A) & set(files_B)
# common_files = set(files_A) - set(files_B)
if not common_files:
print("未找到同名文件。")
return
# 复制同名文件到文件夹C
copied_count = 0
for file_name in common_files:
# 这里选择从folder_A复制你也可以改为从folder_B复制或同时复制两个版本
source_path = os.path.join(folder_A, file_name)
dest_path = os.path.join(folder_C, file_name)
shutil.copy2(source_path, dest_path)
print(f"已复制: {file_name}")
copied_count += 1
print(f"\n复制完成!共复制 {copied_count} 个文件。")
except Exception as e:
print(f"操作出错: {e}")
# 使用示例
if __name__ == "__main__":
# 请修改为你的实际路径
folder_A = r"R:\TYSAR-德清院\B-模型处理-预标注\20250818-不分类-处理20250906\人工检查\Group_6\png_txt" # 替换为第一个文件夹路径
folder_B = r"R:\TYSAR-德清院\B-模型处理-预标注\20250818-不分类-处理20250906\人工检查\剔除空标注\G6" # 替换为第二个文件夹路径
folder_C = r"R:\TYSAR-德清院\B-模型处理-预标注\20250818-不分类-处理20250906\人工检查\Group_6\d" # 替换为目标文件夹路径
copy_matching_files(folder_A, folder_B, folder_C)