如何将多个图像重命名为两个不同的名称?

时间:2019-03-07 09:54:08

标签: python python-3.x rename enumerate

我需要使用Python重命名文件夹中的992图片名称。图像的名称应根据其顺序更改。例如

current name
image_1 should rename to P1_ES_1
image_2 should rename to P1_ES_2
image_3 should rename to P1_ES_3
image_4 should rename to P1_ED_1
image_5 should rename to P1_ED_2
image_6 should rename to P1_ED_3

对于下六个图像再次重复相同的操作,只是“ P”将发生如下变化:

image_7 should rename to P2_ES_1
image_8 should rename to P2_ES_2
image_9 should rename to P2_ES_3
image_10 should rename to P2_ED_1
image_11 should rename to P2_ED_2
image_12 should rename to P2_ED_3

我已经摘录的代码片段将更改前六个图像的附件显示名称,这与我所需要的不一样。enter image description here

以下是代码段:

import os
import glob

path = 'F:/my_data/imagesResized/'

def rename_files(): 

 j = 1
 i = 1

 for i, filename in enumerate(glob.glob(path + '*.png')): 

    os.rename(filename[:], os.path.join(path, 'P' + str(i) + '_'+ "ES" + '_' + str(j) + '.png'))

    j += 1

if __name__ == '__main__': 

    rename_files() 

2 个答案:

答案 0 :(得分:1)

最简单的方法是使用modulo运算符循环索引。您使用enumerate做的正确。另一个有趣的事实是,使用sorted使用glob对图像进行相应排序,有时文件名以随机顺序出现:

fns = sorted(glob.glob(path + '*.png')): 

es_or_ed = 'ED'

for i, fn in enumerate(fns):
    # Check for ED or ES
    if i % 3 == 0 and es_or_ed == 'ES':
        es_or_ed = 'ED'

    elif i % 3 == 0 and es_or_ed == 'ED':
        es_or_ed = 'ES'

    # Create new filename
    new_fn = 'P{}_{}_{}.png'.format(i // 6 + 1, es_or_ed, i%3+1)

    # rename...
    os.rename(fn, os.path.join(path, new_fn))

对于随机图像,这会给你

 old: image_1     new: P1_ES_1
 old: image_2     new: P1_ES_2
 old: image_3     new: P1_ES_3
 old: image_4     new: P1_ED_1
 old: image_5     new: P1_ED_2
 old: image_6     new: P1_ED_3
 old: image_7     new: P2_ES_1
 old: image_8     new: P2_ES_2
 old: image_9     new: P2_ES_3
 old: image_10    new: P2_ED_1
 ...

答案 1 :(得分:0)

我会做

def build_file_name(files): 
    p_order = 1
    current_e = "ES"
    current_e_order = 1

  for file_name in files:
    file_sections =  file_name.split('.')
    file_name = file_sections[0] #this holds file name without extension
    extension = file_sections[1] # this holds extension
    new_file_name = []
    file_order = int(file_name.split('_')[1].strip()) # Incause you're sure that it's always image_{some_number}

    current_e_order = current_e_order + 1

    new_file_name.append("P" + str(p_order))
    new_file_name.append("_")
    new_file_name.append(current_e)
    new_file_name.append("_")
    new_file_name.append(str(current_e_order))
    new_file_name.append(extension) #append extension back
    if file_order % 6 == 0:
        p_order = p_order + 1
    if file_order % 3 == 0:
        current_e = "ED" if current_e == "ES" else "ES"
        current_e_order = 1
    final_file_name = ''.join(new_file_name) # build normal path now.