gpt4 book ai didi

python - 无法重命名多个文件(Python)

转载 作者:太空宇宙 更新时间:2023-11-03 14:40:31 24 4
gpt4 key购买 nike

我正在尝试重命名一些文件,但我无法弄清楚。

这些是我要重命名的文件:

src

它们从 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_area13ex_area14 应为 ex_area11ex_area12 等等。

谢谢

最佳答案

我正在考虑这样的事情:

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

关于python - 无法重命名多个文件(Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46582969/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com