Files
CleanUnpairedFiles/main.py
wangjialiang 2f4a23d0ee First
2025-11-12 17:09:36 +08:00

48 lines
1.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import os
import shutil
def split_and_move_paired(folder, ext1, ext2, dest1, dest2):
"""
只移动一比一配对的文件(如 a.tiff 与 a.xml
folder: 原始文件夹
ext1, ext2: 扩展名,例如 '.tiff', '.xml'
dest1, dest2: 对应目标文件夹
"""
os.makedirs(dest1, exist_ok=True)
os.makedirs(dest2, exist_ok=True)
# 收集文件名(不含扩展名)
files_ext1 = {os.path.splitext(f)[0] for f in os.listdir(folder) if f.lower().endswith(ext1.lower())}
files_ext2 = {os.path.splitext(f)[0] for f in os.listdir(folder) if f.lower().endswith(ext2.lower())}
# 求交集:表示两种文件都存在的名字
paired_files = files_ext1 & files_ext2
moved_count = 0
for name in paired_files:
src1 = os.path.join(folder, name + ext1)
src2 = os.path.join(folder, name + ext2)
dst1 = os.path.join(dest1, name + ext1)
dst2 = os.path.join(dest2, name + ext2)
# 移动两个文件
try:
shutil.move(src1, dst1)
shutil.move(src2, dst2)
moved_count += 1
print(f"✅ 已移动配对文件: {name}{ext1}{name}{ext2}")
except Exception as e:
print(f"⚠️ 移动失败 {name}: {e}")
print(f"\n总计成功移动 {moved_count} 对文件。")
print(f"剩余未配对文件已留在原目录中。")
if __name__ == "__main__":
folder = r"E:\Train\裁剪EM14新\Output" # 原始文件夹
ext1, ext2 = ".tiff", ".xml"
dest1 = r"E:\Train\EM14IMG" # 存放 .tiff 文件的目录
dest2 = r"E:\Train\EM14XML" # 存放 .xml 文件的目录
split_and_move_paired(folder, ext1, ext2, dest1, dest2)