需要事先安装shutil库
pip install pytest-shutil
实现代码:
import os
import random
import shutil
saveBasePath = '/home/aistudio/PaddleDetection/dataset/'
# 要移动的文件名目录,存放在txt文件夹下
listDir = os.path.join(saveBasePath, 'voc/VOCdevkit/VOC2007/ImageSets/test_all.txt')
#要移动的文件目录
fileDir = os.path.join(saveBasePath, 'voc/VOCdevkit/VOC2007/JPEGImages/')
#目标目录
tarDir = os.path.join(saveBasePath, 'coco/val2017/')
# 查看要移动的列表
with open(listDir, 'r') as f:
s = f.readlines()
pathDir = os.listdir(fileDir) #scan
filenumber = len(pathDir)
count = 0
for i in s:
j = i[:-1]+'.jpg'
if(j in pathDir):
shutil.move(fileDir + j, tarDir + j)
count += 1
# 打印信息
print('total :{} pictures'.format(filenumber))
print('succeed moved {} pictures from {} to {}'.format(count, fileDir, tarDir))
print('residue :{} pictures'.format(filenumber-count))