Search code examples
pythonrenameglob

Can't rename multiple files (Python)


I am trying to rename some files but I can't figure it out.

These are the files I want to be renamed:

src

Their are counted from 13 because there are other imges before but they are deleted (so just these remains)

With this code nothing is done.

for (cnt,contours) in cnts:
    idx += 1
    x,y,w,h = cv2.boundingRect(cnt)
    roi = gray1[y:y + h, x:x + w]
    cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
    cv2.rectangle(thresh_color,(x,y),(x+w,y+h),(0,255,0),2)
    cv2.imshow('img',img)
    cv2.waitKey(0)
    if (w * h >= 180 * 30):
        cv2.imwrite(os.path.expanduser('~\\Desktop\\FOLDER\\ex_area1') + str(idx) + '.tif', roi)


files = glob.glob(os.path.expanduser('~\\Desktop\\FOLDER\\ex_area1') + str(idx) + '.tif')
for file in files:
    parts = file.split('_')
    new_name = 'ex_{}'.format(parts[0])
    os.rename(file, os.path.join(os.path.dirname(file),new_name))

idx is a counter which increment the number by one for every image. It's declared above this code in the program.

How can I rename these "new" images again ?

ex_area13 and ex_area14 should be ex_area11, ex_area12 and so on..

Thanks


Solution

  • Solved with this code. It's also ignores errors due to overwrite. For me is working great.

    try:
        path = (os.path.expanduser('~\\FOLDER\\')) #path to images folder
        files = os.listdir(path)
    
    idx = 0  #counter
    
    for file in files:  #search for files..
            idx =+ 1
            i = 'ex_area1'  #name of the file I search for and which will be renamed
            if file.endswith('.tif'):  #search only for .tif
                i = i + str(idx)  #add to i the i+counter (namefile+counter)
                os.rename(os.path.join(path, file), os.path.join(path, str(i) + '.tif'))
    
    except OSError as e:
            if e.errno != errno.EEXIST:   #if there are errors of overwrite, ignore them
                raise