我正在尝试重命名某些文件,但我无法弄清楚。
这些是我想要重命名的文件:
他们从13计算,因为之前还有其他图像,但它们被删除(所以只剩下这些图片)
使用此代码无需执行任何操作。
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
是一个计数器,它为每个图像增加一个数字。它已在程序中的此代码上方声明。
如何重命名这些" new"图像又来了?
ex_area13
和ex_area14
应为ex_area11
,ex_area12
等等。
由于
答案 0 :(得分:1)
我在考虑这样的事情:
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))
打印:
./ex_area13.tif --> ./ex_area11.tif
./ex_area14.tif --> ./ex_area11.tif
答案 1 :(得分:0)
解决了这段代码。它也会忽略因覆盖而导致的错误。对我来说工作很好。
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