python - Fixing different id having same images in a csv column by renaming? -


as new python programmer, i'm having trouble figuring out how accomplish following.

given input data csv file:

sku     image_name b001    a.jpg b002    a.jpg b001    b.jpg b002    c.jpg b003    x.jpg 

where multiple sku's might have same image name. when occurs, want rename image name in image__name column concatenating "_" + sku value shown image name in same row.

so desired output data be:

sku     image_name b001    a_b001.jpg b002    a_b002.jpg b001    b.jpg b002    c.jpg b003    x.jpg 

after should rename images in image folder according image_name column.

this have far:

import csv  #open , store csv file open('d:\\test.csv', 'rb') csvfile:     spamreader = csv.reader(csvfile, delimiter=',') 

ok, you've got quite ways go, should give hints on how proceed (assuming reasonable number of files):

import csv os.path import splitext  open("/tmp/test.csv", 'rb') csvfile:     itemlist = []     renamedlist = []     keylist = []     spamreader = csv.reader(csvfile, delimiter=",")     row in spamreader:         keylist.append(row[0])         itemlist.append(row[1])         renamedlist.append(row[1]) tobechanged = [itemnum itemnum, item in enumerate(itemlist)                  if itemlist.count(item) > 1] itemnum in tobechanged:     name, ext = splitext(itemlist[itemnum])     renamedlist[itemnum] = '{}_{}{}'.format(name, keylist[itemnum], ext)  # @ point have desired info , can print  # have above print("sku\timage_name") row in zip(keylist, itemlist):     print(row[0] + '\t' + row[1])  # duplicating / renaming files next. isn't way # (or efficient), it's easy way understand. # idea first make copies of needed files... shutil import copyfile changednames = [] itemnum in tobechanged:     copyfile(itemlist[itemnum], renamedlist[itemnum])     changednames.append(itemlist[itemnum]) # ...and delete originals. set used eliminate # duplicates. os import remove item in set(changednames):     remove(itemname) 

there lots of ways can improve code. intent here make more understandable. understand first, improve second.


Comments

Popular posts from this blog

jOOQ update returning clause with Oracle -

java - Warning equals/hashCode on @Data annotation lombok with inheritance -

java - BasicPathUsageException: Cannot join to attribute of basic type -