问题描述:同事给了我一堆只有xml文件的文件夹,又给了一些含有xml文件对应的jpg文件(jpg文件数目大于xml文件数目),让我帮他把xml文件对应的jpg文件挑出来。
解决方法:
一、手动
如果数量很少,可以直接将xml文件复制进jpg文件中,然后点击大图标查看,如下所示
会发现,一张jpg对应一个xml文件,手动删除没有xml文件的jpg文件。
二、
文件特别多,这时只需要一个简单的python代码即可实现
如下:
import json import shutil,os path = 'D:/pythonpy/' //xml和jpg混合文件所在的位置 filelist = os.listdir(path) picturelist=[] //存放图片 for file in filelist: if( ".xml" in file ): //找到xml文件 picture1 = file.split(".",1) //用“.”来分割文件名 picture=picture1[0] //得到文件名 picturelist.append(picture) else: continue for picture in picturelist: shutil.copy("D:/pythonpy/"+picture, "D:/pythonpy/pic") //将path下的xml对应的jpg文件存入另一文件夹中
前提是:path里必须有xml对应的jpg文件,而且另一文件夹中不能有该文件。
我是一个刚入门python的新手,上面都是自己写的,大家尽管拿去用,另外也是方便自己回顾。如有错误,接受批评指正。