基础语法
-
os.path.join()
路径拼接 -
os.listdir()
返回一个list,list里面是括号内文件夹里的文件(夹)的名字 -
os.path.splitext(file)
分离文件名和扩展名
例:dog.jpg,文件名=dog,扩展名='.jpg' -
os.path.exists()
返回True或False,判断存不存在 -
shutil.move(file_path_0, file_path_1)
填【文件】的前后【路径】(位置)
代码
我的标签是VOC格式,所以用root拼接路径比较方便。大家按需修改,也可以直接写两个folder的绝对路径
import os
import shutil
root = 'X:/path/...'
img_folder = os.path.join(root, 'DOG_img') # 改成自己的文件名
xml_folder = os.path.join(root, 'Annotations') # 改成自己的文件名
# 如果没有文件夹则创建
img_destination_folder = os.path.join(img_folder, 'img 没有标签')
xml_destination_folder = os.path.join(xml_folder, '标签没有对应img')
for folder in [img_destination_folder, xml_destination_folder]:
if not os.path.exists(folder):
os.makedirs(folder)
def move_files(source_folder, comparison_folder, destination_folder):
source_files = os.listdir(source_folder)
comparison_files = os.listdir(comparison_folder)
jpg_or_xml_files = [file for file in source_files if file.endswith((".jpg", ".xml"))]
for file in jpg_or_xml_files:
name, ext = os.path.splitext(file) # 分离文件名和扩展名。
# dog.jpg,name=dog, ext='.jpg'
# 开始匹配
if ext == '.jpg':
name = name + '.xml'
else:
name = name + '.jpg'
if name not in comparison_files:
source_file_path = os.path.join(source_folder, file)
destination_file_path = os.path.join(destination_folder, file)
if os.path.exists(source_file_path): # 如果路径存在则继续运行代码
shutil.move(source_file_path, destination_file_path)
print(f"Moved file: {file} to {destination_folder}")
if __name__ == '__main__':
move_files(img_folder, xml_folder, img_destination_folder)
move_files(xml_folder, img_folder, xml_destination_folder)