2016-07-05 33 views
0

Python的初学者在这里。命名文件带有图案

我有数百命名为(按顺序)图像文件的目录:

002_IMG_001,002_IMG_002,002_IMG_003,002_IMG_N

现在,我想重新命名这些图像,使得五在一排文件有“N”从1:5,即每一套连续五个图像得到N,1至5我还要数“N”之前,粘另一个字符串。此字符串将跟踪这一集N个图像,e.g,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,...

+0

我不知道如果我理解你的重命名规则。你能提供一个具体的例子吗? –

+0

所以他们去001 ...,002 ...,003 ...? –

+0

确认要将此文件名002_IMG_001变成什么 - 这个回答没有评论 – PyNEwbie

回答

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'] 
+0

Exatcly我需要的输出。只有一点意见:我们还需要访问for循环中的原始文件名,以在最后重命名文件 - 可能是嵌套for循环?你有什么建议吗? – wheatSingh

+0

我刚编辑了代码。无需嵌套另一个循环。请参阅'for'循环中的'enumerate'关键字。这使'for'循环中的索引和列表项都可用。我有另一个建议。 listdir可能不一定按字母顺序列出目录项。您可能希望在循环之前添加语句“fileList.sort()”语句。不要为该陈述分配任何东西。它将原始列表永久分类。 – Joe

+0

添加“fileList.sort()”,它的工作方式就像一个魅力。非常感谢 ! – wheatSingh