使用模式

时间:2016-07-05 22:33:52

标签: python file-io file-rename

Python初学者。

我有一个包含数百个图像文件的目录(按顺序):

002_IMG_001,002_IMG_002,002_IMG_003,002_IMG_N

现在,我正在尝试重命名这些图像,使得连续的五个文件从1:5开始具有'N',也就是说,每个连续的五个图像集得到N,1到5.我还想在数字'N'之前粘住另一个字符串。该字符串将跟踪N个图像的集合,例如IMG_001_1,IMG_001_2,... IMG_001_N,IMG_002_1,IMG_002_2,... IMG_00X_N

Mac上的python 2.7.10上的伪代码如下所示:

import os

myDir = "/Users/path/to/dir/"
fileList = os.listdir(myDir)

for filename in fileList :
    #split the images into sets of five each
    newFile = 'IMG_' + '00' + X + '_' + N
        #loop through images and rename
            os.rename(fileName, newFile)

我想我需要一个循环条件,如:

 if int(filename[9:12]) % 5 == 0

但这意味着,我必须为1到5创建五个单独的条件,这似乎不对。任何提示都会受到赞赏吗?

编辑:一些人不清楚需要什么样的输出。我正在寻找一个函数来获取最终文件名,如:IMG_001_1,IMG_001_2,... IMG_001_5,IMG_002_1,IMG_002_2,... IMG_002_5,......

1 个答案:

答案 0 :(得分:0)

我认为这应该有效:

my_list = ["002_IMG_001", "002_IMG_002", "002_IMG_003", "002_IMG_004", "002_IMG_005",
       "002_IMG_006", "002_IMG_007", "002_IMG_008", "002_IMG_009", "002_IMG_0010",
       "002_IMG_011", "002_IMG_012", "002_IMG_013", "002_IMG_014", "002_IMG_015",
       "002_IMG_016", "002_IMG_017", "002_IMG_018", "002_IMG_019", "002_IMG_0020",
       ]
fileList.sort()

print("Original list:\n")
print(fileList)

new_list = []

for index, old_file_name in enumerate(fileList):
    group, subgroup = divmod(index,5)
    group, subgroup = group + 1, subgroup + 1
    new_file_name = "IMG_{0:03d}_{1}".format(group, subgroup)
    new_list.append(new_file_name)

    os.rename(old_file_name, new_file_name)

print("\nNew list:\n")
print (new_list)

这是输出:

Original list:

['002_IMG_001', '002_IMG_002', '002_IMG_003', '002_IMG_004', '002_IMG_005', 
'002_IMG_006', '002_IMG_007', '002_IMG_008', '002_IMG_009', '002_IMG_0010', 
'002_IMG_011', '002_IMG_012', '002_IMG_013', '002_IMG_014', '002_IMG_015', 
'002_IMG_016', '002_IMG_017', '002_IMG_018', '002_IMG_019', '002_IMG_0020']

New list:

['IMG_001_1', 'IMG_001_2', 'IMG_001_3', 'IMG_001_4', 'IMG_001_5', 
'IMG_002_1', 'IMG_002_2', 'IMG_002_3', 'IMG_002_4', 'IMG_002_5', 
'IMG_003_1', 'IMG_003_2', 'IMG_003_3', 'IMG_003_4', 'IMG_003_5', 
'IMG_004_1', 'IMG_004_2', 'IMG_004_3', 'IMG_004_4', 'IMG_004_5']