只更改文件名
的一部分,我有我的文件夹中的这些图片:只更改文件名
- area11.tif
- area12.tif
- area14.tif
- area21.tif
- area22.tif
- area25.tif
how ca ñ我只更改最后一位数字,以便它们变得有序并且“更多增量”? 相反,如果area14.tif
它应该是area13.tif
和area22/area25相同的东西。
我有一个代码,但它有点破,因为它删除了一些文件(这很奇怪,我知道...)。
编辑:添加(也许破..)代码
try:
path = (os.path.expanduser('~\\FOLDER\\'))
files = os.listdir(path)
idx = 0
for file in files:
idx =+ 1
i = 'ex_area'
if file.endswith('.tif'):
i = i + str(idx)
os.rename(os.path.join(path, file), os.path.join(path, str(i) + '.tif'))
except OSError as e:
if e.errno != errno.EEXIST:
raise
1)阅读目录中的文件名到数组(串)。
2)迭代文件名
3)对于每一个文件名的阵列上方,片串和插入索引
4)重命名
例如:
import os
import glob
[os.rename(n, "{}{}.tif".format(n[:5], i)) for i, n in enumerate(glob.glob("area*"))]
我试着在后来实际使用生成的列表时尝试理解。 –
@DavisHerring为了便于阅读而更新。谢谢 –
@ VladLyga它只增加area2的最后一位数字。也许我做错了什么..现在双重检查.. – Link
首先你获得的列表中图像pathes使用glob模块:
images = glob.glob("/sample/*.tif")
那么你只需要重新命名他们都与操作系统模块:
for i in range(len(images)): os.rename(images[i], ‘area’+i+’.tif’)
首先重命名所有文件名临时名称,然后添加你喜欢的任何名称
import glob,os
images = glob.glob("*.tif")
for i in range(len(images)):
os.rename(images[i], 'temp_'+str(i)+'.tif')
tempImages = glob.glob("temp*.tif")
for i in range(len(tempImages)):
os.rename(tempImages[i], 'area'+str(i+1)+'.tif')
也发现了这个其他的解决办法。但是这个有一个小小的区别,最后做一个更好的工作方式(至少对我来说):为每个区域创建一个文件夹。这么简单,我以前没有想到...
顺便说一句,这里是代码,评论。我正在使用这个,只是因为我达到了我想要的。感谢所有回答,让我学习新事物。
path = (os.path.expanduser('~\\FOLDER\\AREA1\\')) #select folder
files = os.listdir(path)
i = 1 #counter
name = 'area' #variable which the file will take as name
for file in files:
if file.endswith('.tif'): #search only for .tif. Can change with any supported format
os.rename(os.path.join(path, file), os.path.join(path, name + str(i)+'.tif')) #name + str(i)+'.tif' will take the name and concatenate to first number in counter. #If you put as name "area1" the str(i) will add another number near the name so, here is the second digit.
i += 1 #do this for every .tif file in the folder
这有点简单,但因为我把文件放在两个单独的文件夹中。如果将这些文件保存在同一个文件夹中,这将无法正常工作。
编辑:现在,我看到了,它与我上面的代码一样....
为什么你在意?你不能只用glob吗? – cwallenpoole
我很在意,因为我需要他们为此后的流程订购。 现在我正在阅读有关正则表达式的东西..可能是这样吗? – Link
哪部分你有麻烦?一般重命名文件还是特别按顺序编号? – Mark