Reputation: 2269
I am trying to rename some files but I can't figure it out.
These are the files I want to be renamed:
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
Upvotes: 1
Views: 92
Reputation: 2269
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
Upvotes: 0
Reputation: 18916
I'm thinking of something like this:
import os
folder = "."
#tif_files = [i for i in os.listdir(folder) if i.endswith(".tif")]
tif_files = ["ex_area13.tif","ex_area14.tif"]
for ind, file in enumerate(tif_files):
new_name = "ex_area{}.tif".format(str(ind+11).zfill(2)) #11,12... can be changed to 001,002... or other
oldpath = os.path.join(folder,file)
newpath = os.path.join(folder,new_name)
#os.rename(oldpath,newpath)
print("{} --> {}".format(oldpath,newpath))
Prints:
./ex_area13.tif --> ./ex_area11.tif
./ex_area14.tif --> ./ex_area11.tif
Upvotes: 1