我要匹配图片后修改图片名称,可以直接改名,不过这样的话就会造成匹配成功的文件和没有匹配到的文件混合在一起
最简陋的方式
# -*- coding: utf-8 -*-import osimport os.pathimport shutilrootdir = 'F:/temporary_dowload/img' # 指明被遍历的文件夹 sp={ 'DSC_0549':'020403008', 'DSC_0550': '020403008',}for parent,dirnames,filenames in os.walk(rootdir): #三个参数:分别返回1.父目录 2.所有文件夹名字(不含路径) 3.所有文件名字 for filename in filenames: #输出文件信息 prefile = filename.split(".")[0] try: targetfile = sp[prefile]+".jpg" print ("targetfile:"+targetfile) sourcepath = os.path.join(parent,filename) targetpath = os.path.join('F:/temporary_dowload/img2', targetfile) shutil.copy(sourcepath, targetpath) except: print("pass") pass
这种方式是除了数据有问题到时copy出错,否则没有转换的问题,我推荐用这一种,我就遇到这样的问题,我用这个程序改图片的名字总是出错,会出现要copy图片的数量和
copy了的图片数量有差别,先我以为是程序写的有问题,然后我就重写了,直接从Excel里面读数据进行操作,结果还是出现原先问题,我想快点完成工作,然后就想把匹配到 的图片和没匹配的图片进行比对,把重合和重合的图片进行比对,还是出错,总是缺少图片没有对上数据
#coding:utf-8import xlrdimport xlwtimport osimport osimport os.pathimport shutilpath_list = []goods_list = []goods = xlrd.open_workbook('D:\Excel\huaguan\cc\cc\cc2.xlsx')#打开文件sh = goods.sheet_by_index(0)#返回第几页的对象for rx in range(sh.nrows): if rx: goods_list.append(sh.row_values(rx))print goods_list[0][1]print len(goods_list)wb = xlwt.Workbook()#创建工作簿,设置字符编码ws = wb.add_sheet('Sheet1')#创建sheetcc = []rootdir = 'D:\Excel\huaguan\picture\picture'for parent,dirnames,filenames in os.walk(rootdir): #三个参数:分别返回1.父目录 2.所有文件夹名字(不含路径) 3.所有文件名字 for filename in filenames: prefile = filename.split(".")[0] path_list.append(prefile) cc.append(filename)# for path in path_list:# for c in range(0,20):# print cr = 0file_list = {}p =0for path in path_list: for c in range(0,len(goods_list)): if str(goods_list[c][6])==path: print 'successful' ws.write(r, 1, goods_list[c][1]) ws.write(r, 2, goods_list[c][6]) f = os.path.join('D:\Excel\huaguan\picture\picture',cc[p]) to = str(goods_list[c][1])+'.'+cc[p].split(".")[1] # to = str(int(goods_list[c][1])) # to = os.path.join('D:\Excel\huaguan\picture\cc3',to) to = os.path.join('D:\Excel\huaguan\picture\cc3',to) file_list[cc[p]] = to print p print cc[p] print to # print f,to # with open(f, 'rb'): # os.rename(f, to) # open(to,"wb").write(open(f,"rb").read()) shutil.copy2(f,to) p += 1 r = r + 1 os.remove(f)print len(goods_list)print len(path_list)wb.save('test.xls')print 'successful' # os.remove(path)
找了好几天才找到问题的所在,原来是原先处理的Excel数据有些数据有问题,例如要更改的图片的名字有重合,或者是图片找不到还有个别特别情况
做完之后发现,像这样的数据最好用Excel本身相关函数来写,扩展操作多了反而不好,搞到最后其实是Excel数据处理的问题,所以要在开始的时候搞清楚问题,不然思路偏了,那时间耽搁的不是一会半会,再次处理同样的数据,我就先把要处理的Excel数据格式转换为我需要的数据格式,查询要处理的数据有没有经常出现的错误:如数据缺零,数据重复,然后用最简陋的方式进行处理,得到数据有错误,分析是哪里出错,程序出错还是数据出错,数据出错就对数据进行处理,不建议重写程序再处理数据